Archive

Posts Tagged ‘JQuery’

Beginners Guide to DOM Selection with jQuery

Categories: .Of Interest Tags: ,

Google Docs spreadsheet script: compare dates, highlight past dates, highlight weekends, and highlight today

October 30, 2013 Leave a comment
screenshot of Google spreadsheet with 3 custom highlighting functions applied

A Google spreadsheet with my 3 custom highlighting functions applied

ORIGINAL PROBLEM

I spent hours tonight struggling with this Google Apps script I wrote to serve as custom functions or advanced macros. I adapted it from this StackOverflow post. The main issue I ran into was comparing dates. Here is my research path, and hopefully, some indicator as to why it took so long:

STEPS and MISSTEPS TAKEN TO SOLVE

  • Looked for built-in function in Google spreadsheet to do conditional formatting on weekends. No weekend selector and no built-in way to conditionally format the whole row based on the contents of one cell. (time: 35 min)
  • Discovered the only way to do this was to write a Google Apps script. I’ve never heard of Google Script until today. Now I had to look up basic Google Script tutorials. (time: 1 hr 30 min)
  • Wrote and tested code to highlight weekends. Date functions worked fine. (time: 1 hr)
  • Wrote code to highlight dates older than today. Worked, but highlighted today’s date also, which is incorrect. Investigated this issue for almost 2 hours. (time: 1 hr 38 min)
  • Discovered that Google Apps script is based heavily on JavaScript. Was then able to research from a JavaScript perspective. Ok, I should be almost there right?-Wrong! The major stumbling block I ran into has to do with how JavaScript handles date comparisons. There were two main problems:
    1. The new Date() object was not comparing correctly to today’s date. The issue, I found, is well-known to many JavaScript developers: comparing two Date() objects includes the time component, down to the millisecond, so they are never going to be equivalent. (it’s issues like these that make working with libraries like jQuery and Backbone more desirable than raw JavaScript coding.)The solution to this problem was to remove the time component with toDateString(). (time: 30 min)
    2. But that still didn’t make the comparisons work. The issue had something to do with comparing two objects. The solution was given on StackOverflow as essentially converting date objects to strings before comparing. I found the way to do that was with the dot operator and the non-intuitive getTime() function. (time: 15 min)
  • There was still one more snag though. Apparently you can’t assign the getTime()¬†component in a variable like this:
    var today_noTime = new Date(today.toDateString().getTime());
    

    because it just fails. I’m not sure of the technical reasons for this, but it is very annoying in practice.The ultimate solution was to use getTime() as a dot-method on your Date() objects in the direct comparison statement, like this:

    if (today_noTime.getTime() == date_noTime.getTime()) {
        Logger.log("****** Dates are EQUAL ******");
    }

    (time: 15 min)

CONCLUSION

It took around 5 hrs to finally find all the answers. Along the way, I struggled a bunch, learned a lot and am grateful for the experience. However, my one real frustration was that there was no one clear website saying “known issues with comparing time and date in JavaScript”–there was just no such thing. I hope that this post has explained some of these issues precisely enough that it will save you some time.

FINAL SCRIPT

Here is the final complete script:

/*
 * Creator: Eric Hepperle
 * Date:    10/29/13
 * Purpose: Google Script for Spreadsheet.
 *           - Shades rows with weekend dates in (column 2) light gray.
 *           - Shades rows for past days with dark gray.
 *           - Highlights today with yellow background.
 *
 * Notes:   Adapted from code found here:
 *           http://stackoverflow.com/questions/15730638/
 *           google-doc-spreedsheet-conditional-formatting-script
 *
 * Colors:
 *           #B8B8B8 = med gray; past dates.
 *           #E8E8E8 = light gray; weekends.
 */
function colorAll() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var startRow = 6;
    var endRow = sheet.getLastRow();

    for (var r = startRow; r <= endRow; r++) {
        colorRow(r);
    }
}

function colorRow(r) {
    var sheet = SpreadsheetApp.getActiveSheet();
    var dataRange = sheet.getRange(r, 1, 1, 5);

    var data = dataRange.getValues();
    var row = data[0];

    // eric's vars
    var date = row[1]; // 2nd column
    var dayOfWeek = date.getDay();

    Logger.log("*** Logging dayOfWeek " + r + " now ***");
    Logger.log(dayOfWeek);

    // if dayOfWeek is Sat or Sun:
    if (dayOfWeek == 0 || dayOfWeek == 6) {
        if (row[0] === "") {
            dataRange.setBackgroundRGB(255, 255, 255);
        } else {
            dataRange.setBackground("#E8E8E8");
        }
    }

    var today = new Date();
    Logger.log("*** today ***");
    Logger.log(today);
    Logger.log("*** date ***");
    Logger.log(date);

    // remove time component from date for comparison
    today_noTime = new Date(today.toDateString());
    date_noTime = new Date(date.toDateString());

    /*
	Logger.log("today_noTime:");
	Logger.log(today_noTime);

	Logger.log("date_noTime:");
	Logger.log(date_noTime);

	if(today_noTime.getTime() == date_noTime.getTime()){
		Logger.log("****** Dates are EQUAL ******");
	}
    */

    // if date is older than today, mark it as such
    if (date_noTime.getTime() < today_noTime.getTime()) {
        dataRange.setBackground("#B8B8B8");
    }

    if (date_noTime.getTime() == today_noTime.getTime()) {
        dataRange.setBackground("yellow");
    }

    SpreadsheetApp.flush();
}

function onEdit(event) {
    var r = event.source.getActiveRange().getRowIndex();
    if (r >= 2) {
        colorRow(r);
    }
}

CodeSlayer2010’s Code: jQuery Fancy Paragraph Styling (manila background, rounded-rectangle, drop-shadow, orange border)

screenshot of Eric CodeSlayer2010 Hepperle's jsfiddle jQuery -- fancy paragraph tag style 01

Jsfiddle Screenshot (07/13/13)

I wrote this jQuery in about 5 minutes. It is really simple, but amazingly powerful at the same time. The purpose of this is to instantly style paragraph tags. Here are the style parameters:

Background color: Manila (light beige-ish/yellow)
Border color: Orange
Drop-shadow: Yes
Rounded-rectangle: Yes

I want to make the code easily available to everyone, so I’ve provided the jQuery here in case you want to quickly add this style to your project. Cheers.

-CodeSlayer2010

/* Add manilla background, rounded-rect, orange border,
 & shadow to paragraphs.
 (Press F12 in your browser to see the results)

 @Creator: Eric Hepperle (CodeSlayer2010)
 @Date: 07/13/13
 @Version: 1.0

 @Purpose: Puts a fancy style on paragraph <P>
 tags to make them 'pop'.

 @Updates:
 07/13/13
 8:30 - Created initial code.

*/

console.clear()

$('p').css({
 'border': 'solid #FFB819 3px',
 'border-radius':'15px',
 'box-shadow': '10px 10px 5px #888888',
 'background-color':'#FFFBCC',
 'padding':'15px'
});

Image Auto Resize / Scaling with JQUERY – Stack Overflow

November 12, 2012 Leave a comment
Categories: .Of Interest Tags: , ,

Create jQuery Plugin Tutorials

March 2, 2012 1 comment

JQuery

Here are two excellent jQuery plugin tutorials.  My goal by posting these two links is to try to save you guys some time in searching through all the other links for the right one.  Here you go:

Testing WordPress’s Code Syntax Highlighting

December 4, 2011 1 comment

(12/04/11)

TEST 1:

This example introduces a bit of test code we are calling ‘CODE SNIPPET A’. It uses the ‘sourcecode’ tag and has no language attributes or parameters.

Code Snippet A

		<form id="form1">
			<div>
				<input id="btnShowMessage" type="button" value="show message" />
				<div id="divMessage" style="background-color: yellow;">THIS IS THE MESSAGE</div>
			</div>
		</form>
	

NOTE: When you are in your dashboard editing your post you will not be able to see the syntax highlighting. Don’t freak out. Do a save and ‘preview’ and everything should be just fine.

TEST 2:

This is snippet A except now we have added the language=’html’ attribute.

	<form id="form1">
		<div>
			<input id="btnShowMessage" type="button" value="show message" />
			<div id="divMessage" style="background-color: yellow;">THIS IS THE MESSAGE</div>
		</div>
	</form>

TEST 3:

Well that’s all good for plain old html. But, what if our code is from a scripting language, such as PHP, that alternates back and forth between html and the script code? In that case, you could use something like

	

Code Snippet B

	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
		<script type="text/javascript">
		  $(document).ready(function(){
			 nameOutput = jQuery('#nameOutput');
			 nameOutput.css({'background':'yellowgreen'});
			 jQuery('body').css({
				'background':'#A66900',
				'font-family':'comic sans ms',
			 });
			 nameOutput.wrap('<span style="color:purple;">');
			 jQuery('#wrap').addClass('centered');
			 jQuery('#wrap').css({
				'background':'#F2B449',
			 })
		  });
		</script>
		<style type="text/css">
		  /****** COLORS *******
			 #A66900 // brown
		   */
		  .centered {
			margin: 0 auto;
			width: 66%;
		  }
		</style>
	<div id="wrap">
		<?php echo "Welcome to " . 'hell'; ?>
		<br />
		<?php

		  echo "<pre>";
		  print_r($_SERVER);
		  echo "</pre>";

		  $model = new stdClass();
		  $model->smurf = 'Papa';
		  echo "my smurf = " . $model->smurf;

		  $model->_name = isset($_POST['userName']) ? $_POST['userName'] : '[not defined!]';
		  echo "<pre>";
		  print_r($model);
		  echo "</pre>";
		?>
		<H1>THIS PAGE IS CURRENTLY UNDER CONSTRUCTION AND TESTING</H1>

		<form id="main" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
		<input type="text" name="userName" value="Enter Your Name" />
		<input type="submit" name="submit" />

		<div id="nameOutput" name="nameOutput">
		  <?php if(isset($_POST['userName'])) echo stripslashes($_POST['userName']); ?>

		</div>
	<div id="content"></div>
	</div>