Javascript / jQuery

Replacing Line Breaks With <br /> Tags Using JavaScript

Posted in Javascript / jQuery, Web Development on February 22nd, 2012 by Steve Marks – Be the first to comment

A scenario arose today where I needed to take the content within a textarea and then output it the screen as HTML. In doing this I knew I would have to take the line breaks in the textarea content (\n) and swap them out for <br /> HTML tags. Languages like PHP come with inbuilt functions to handle this kind of replacement. JavaScript however does not.

I started out by trying the following:

var output = document.form1.myTextarea.value.replace("\n", "<br />");

This kind of worked but only replaced the first line break. I then remembered from previous posts that the JavaScript replace() function will only swap out the first occurrence of a string.

A quick change was required to the code as follows:

var output = document.form1.myTextarea.value.replace(/\n/g, "<br />");

By turning the first parameter into a regular expression and enabling ‘global’ matching (\g), all line breaks were now being converted as expected.

Share

Bring Google Map Markers to Front on Hover

Posted in Javascript / jQuery, Web Development on February 21st, 2012 by Steve Marks – Be the first to comment

When placing markers onto a map using the Google Maps V3 API they will be placed from front-to-back based on their lat/lng. This is normally fine but can cause a problem when there are lots of overlapping markers congregated together, or when the user is viewing the map at a lower zoom level, at which point it can be tricky to select certain markers that have been pushed back.

As a result of the above I needed a way to bring markers to the front when the user hovered their mouse over them. I’ve included the code below but first let’s start with a demonstration of the problem faced and how the code helps:

Try rolling over the markers and you’ll see that the one to the rear will come to the front. This isn’t just limited to two markers either. It will work regardless of the number of markers shown on the map.

Ok, so onto the code:

var map;
// array of markers added to the map
// used at a later date
var markers = new Array();
// a global variable used to store the highest zIndex
// saves calculating it repeatedly
var highestZIndex = 0;

function initialize() {

	/* SETUP MAP */
	var myLatlng = new google.maps.LatLng(52.06768, -1.33758);
	var mapOptions = {
		center: myLatlng,
		zoom: 10,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

	/* ADD 1st MARKER */
	var markerOptions = {
		position: new google.maps.LatLng(52.06768, -1.32058),
		map: map,
		zIndex:1 // important!
	};
	var marker = new google.maps.Marker(markerOptions);
	markers.push(marker);
	// assign a custom variable to this marker containing the zIndex
	marker.set("myZIndex", marker.getZIndex());

	// add mouseover and mouseout events to first marker
	google.maps.event.addListener(marker, "mouseover", function() {
		getHighestZIndex();
		this.setOptions({zIndex:highestZIndex});
	});
	google.maps.event.addListener(marker, "mouseout", function() {
		this.setOptions({zIndex:this.get("myZIndex")});
	});

	/* ADD 2nd MARKER */
	var markerOptions = {
		position: new google.maps.LatLng(52.06768, -1.33758),
		map: map,
		zIndex:2 // important!
	};
	var marker = new google.maps.Marker(markerOptions);
	markers.push(marker);
	// assign a custom variable to this marker containing the zIndex
	marker.set("myZIndex", marker.getZIndex());

	// add mouseover and mouseout events to second marker
	google.maps.event.addListener(marker, "mouseover", function() {
		getHighestZIndex();
		this.setOptions({zIndex:highestZIndex+1});
	});
	google.maps.event.addListener(marker, "mouseout", function() {
		this.setOptions({zIndex:this.get("myZIndex")});
	});

}

function getHighestZIndex() {

	// if we haven't previously got the highest zIndex
	// save it as no need to do it multiple times
	if (highestZIndex==0) {
		if (markers.length>0) {
			// loop through markers
			for (var i=0; i<markers.length; i++) {
				tempZIndex = markers[i].getZIndex();
				// if this zIndex is the highest so far
				if (tempZIndex>highestZIndex) {
					highestZIndex = tempZIndex;
				}
			}
		}
	}
	return highestZIndex;

}

One important thing to note regarding the above is that markers must have a zIndex option set, either by specifying it when adding the marker initially or by using the setOption() function. Without a zIndex, the function getZindex() will return ‘undefined’.

Share

jQuery .find() Not Working in IE with Dynamic XML File

Posted in Javascript / jQuery, PHP, Web Development on August 23rd, 2011 by Steve Marks – Be the first to comment

This problem arose for me when I was loading markers onto a Google map using their JavaScript API via an AJAX call and a returned XML string generated by PHP. The markers would show in all browsers except IE with no errors or warning messages at all. The script seemed to be failing when looping through the XML using jQuery’s .find() function and after hours of debugging I stumbled across the cause of the issue.

The Solution

Looking back the solution seems pretty darn simple (isn’t that all the way!?!) but with no help from our friend Internet Explorer it took some digging around. It turns out the problem was caused by the content type of the string returned to jQuery by the AJAX call not being set and IE not understanding how to deal with it.

To solve the issue I added the following line just before outputting the XML:

header("Content-Type: text/xml");

After adding the above line the jQuery started to loop through the markers with no problem at all.

Share

Adding Numbers or Letters to Google Maps API Markers

Posted in Javascript / jQuery, Web Development on June 4th, 2011 by Steve Marks – 2 Comments

Adding Numbers or Letters to Google Maps API Markers

I’m a huge fan of the Google Maps API and love the amount of features it has to offer. One thing I get asked quite a lot though and that I can’t find in the documentation is “How do I add numbers or letters to the markers?“.

The Solution

The solution is actually quite simple and simply involves you using an image for the marker icons. As part of Google Chart Tools you can generate markers that contain a letter or number, as well change the marker and font colors.

Demonstration

Let’s put it into practice using a simple demonstration:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  function initialize() {
    var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
    var myOptions = {
      zoom: 4,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=A|FF0000|000000'
    });
  }
</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
</body>
</html>

Notice the ‘icon’ option when setting up the marker is a link to an image? This URL contains three key parts that effect the look of the marker:

‘A’ – The letter shown on the marker. This can also be a letter, a symbol, or a combination of them all.
‘FF0000′ – The hex color of the marker
’000000′ – The hex color of the font used

As a result of the above we would get the following:

A Google Maps marker containing a letter

Share

Closing ColorBox From Within an iFrame

Posted in (X)HTML / CSS, Javascript / jQuery, Web Development on May 13th, 2011 by Steve Marks – Be the first to comment

I’ve wrote a couple of posts previously about the jQuery ColorBox plugin. It really is one of my preferred lightboxes that I find myself using more and more as time goes on.

Today I want to answer a question that I’ve been asked a few times before and explain a situation I’ve found myself in a few times during past projects; how can we close the Colorbox from within an iFrame?

Opening The ColorBox

Before I begin to describe the solution let’s take a look at how we open the ColorBox in the first place. To do this we might do something like so:

<script>
	$(document).ready(function(){
		$(".iframeAnchor").colorbox({width:"80%", height:"80%", iframe:true});
	});
</script>
<a class='iframeAnchor' href="colorbox-iframe.html">Open ColorBox</a>

The two key parts here are setting the ‘iframe’ option to true, and specifying the source of the iFrame in the ‘href’ attribute of the link, in this case colorbox-iframe.html. It’s this file where our button to close the ColorBox will reside.

Closing The ColorBox

Now the ColorBox can be opened, let’s look at how we can close it. Using the example iFrame file from above we can simple add the following line of code to colorbox-iframe.html:

<input type="button" name="btnClose" value="Close" onclick="parent.$.colorbox.close()" />

Easy huh? We’re simply calling the standard public method to close a ColorBox button prefixing it with ‘parent.’ to refer to the iFrame’s parent.

Share

Echoing New Lines in JavaScript Alert Box Using PHP

Posted in Javascript / jQuery, PHP, Web Development on May 5th, 2011 by Steve Marks – Be the first to comment

Alert boxes in JavaScript provide a useful way to show the user an error, message or prompt. Adding new lines to one of these alert boxes can be done like so:

alert("This is line one\nThis is line two");

The above bit of JavaScript would output the following:

Reproducing With PHP

At first glance your initial thought on outputting the above using PHP might be to do something as follows:

echo "alert('This is line one\nThis is line two');";

Go ahead, give it a go and you’ll see that the new line is infact ignored and actually results in an error being generated.

The Solution

Solving this is easier than you might think. Simply add a second backslash before the existing one as shown below:

echo "alert('This is line one\\nThis is line two');";

Voila:

Share

Back to Basics: Calling a JavaScript Function on Page Load

Posted in (X)HTML / CSS, Javascript / jQuery, Web Development on March 6th, 2011 by Steve Marks – Be the first to comment

For an experienced developer it is often easy to forget that once upon a time they too struggled with even the easiest of tasks and that not everyone has as much experience as them. The learning curve for developers is a steep one and one that I feel is steepest in the first year or two of building websites and applications. As part of the ‘Back to Basics’ series I aim to put into writing the tasks that I remember getting stuck on or that required research to help other new developers and to ease this learning process.

What I want to talk about today is loading a function written in JavaScript when a page first loads. I have outlined a few simple methods for doing this below that will popup an alert box on the page loading:

Method 1 – Adding an ‘onload’ to the <body> tag

<body onload="alert('Hello World!');">

Method 2 – Using JavaScripts window.onload

<script type="text/javascript">
	window.onload = function() {
		alert("Hello World!");
	}
</script>

Method 3 – Using jQuery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript">
<script type="text/javascript">
	$(document).ready(function() {
		alert("Hello World!");
	});
</script>

By using either of the above 3 methods you will get a popup when the page has finished loading.

Share

Prevent jQTouch Links Going Back or to Homepage

Posted in (X)HTML / CSS, Javascript / jQuery, Web Development on February 23rd, 2011 by Steve Marks – 1 Comment

Thanks to jQTouch making apps for the iOS (and infact any platform) can now be achieved with nothing more than knowledge of HTML, CSS and jQuery. The purpose of this post isn’t to tell you how to make one of these apps (for that I recommend this excellent tutorial) but rather to explain an annoying scenario that I faced during the process.

The Problem

I will presume that in reading this post you already have knowledge of jQTouch and are here due to experiencing the issue in the title; that a link on your page is taking you back a step, or to the homepage, despite you specifying a ‘href’ attribute and the target div existing.

I faced this exact scenario and was stumped for quite a while, especially after not being able to find a solution elsewhere on the web.

Behold… The Solution

After much rejigging and debugging I finally discovered the problem was that the issue was not with the link, but rather it’s placement in the page in that it was nested inside a div. A simplified version of a non-working page can be seen below:

<div id="about">
	<div class="toolbar">
		<h1>About Us</h1>
	</div>
	<div>
		<a href="#contact">Contact Us</a>
	</div>
</div>
<div id="contact">
	<div class="toolbar">
		<h1>Contact Us</h1>
	</div>
</div>

Solution 1

In the above example notice how the link to the ‘Contact Us’ panel is inside a div. I am unsure as to why this doesn’t work but for me I was getting redirected to wrong place. The solution was to instead place the link ouside of the div and, if required, into an unordered list. An amended working version would now look like so:

<div id="about">
	<div class="toolbar">
		<h1>About Us</h1>
	</div>
	<ul>
		<li><a href="#contact">Contact Us</a></li>
	</ul>
</div>
<div id="contact">
	<div class="toolbar">
		<h1>Contact Us</h1>
	</div>
</div>

Solution 2

One of the jQTouch initialisation options is ‘slideSelector’. Any defined selectors in this comma delimited string will act as an identifier to jQTouch alerting the plugin to which links should cause the application to slide to the relevant page. Let’s take the original example and make it work:

The JavaScript:

$.jQTouch({
	slideSelector: 'body > * > ul li a, .slide'
});

The HTML:

<div id="about">
	<div class="toolbar">
		<h1>About Us</h1>
	</div>
	<div>
		<a href="#contact" class="slide">Contact Us</a>
	</div>
</div>
<div id="contact">
	<div class="toolbar">
		<h1>Contact Us</h1>
	</div>
</div>

Notice how we’ve added the ‘.slide’ class as a selector and then added that class to the link itself.

With any luck you will now be getting taken to the correct page when the link is clicked (or should I say tapped). Simple huh? Now go get coding ;)

Share

JavaScript new Date() Returning NaN in IE or Invalid Date in Safari

Posted in Javascript / jQuery, Web Development on February 8th, 2011 by Steve Marks – 4 Comments

When it comes to programming, working with dates can be tricky. Luckily however most languages have done the hard work already and come with some kind of built-in date functionality to assist us. JavaScript inparticular has lots of useful functions to aid in getting, setting and outputting dates.

The JavaScript Date Object

To begin working with dates in JavaScript the first thing you need to do is initialise a date object like so:

var d = new Date();

That’s fine if we want get the current date and time, however it doesn’t help us much if we are planning on working with a date in the past or future. In this instance we would need to pass a date as a parameter to the code above.

The Problem

The problem I wanted to discuss today is specific to Internet Explorer and Safari and is about how passing a date as shown below doesn’t work as expected:

var d = new Date("2011-02-07");
alert(d);

Or:

var d = new Date("2011-02-07T11:05:00");
alert(d);

If you were run the above code snippets across various browsers you would see that in IE you get ‘NaN’ returned and in Safari you get ‘Invalid Date’. Firefox, Chrome and Opera however will output the correct date.

The Solution

The problem lies in the format that you pass the required date to the Date() object. For some reason, and don’t ask me why, the two aforementioned browsers surprisingly do not support the date format “yyyy-mm-dd” and therefore fail. I haven’t managed to compile a definitive list of supported date formats, however I can tell you the following formats are definitely supported across all browsers and would advise sticking to one of these to avoid errors:

var d = new Date(2011, 01, 07); // yyyy, mm-1, dd
var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss
var d = new Date("02/07/2011"); // "mm/dd/yyyy"
var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"
var d = new Date(1297076700000); // milliseconds
var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC

Share

jQuery jqGrid Slow to Respond when Clicking Cells or Rows

Posted in (X)HTML / CSS, Javascript / jQuery, Web Development on January 31st, 2011 by Steve Marks – Be the first to comment

After recently getting stuck into the jQuery grid plugin jqGrid by Tony Tomov and getting a hold on the core functionality, something that came to light relatively quickly was the responsiveness (or lack of) when performing actions on grid events such as ‘onCellSelect’. More than a second pause could generally be expected before the target function was executed.

After a bit of digging around it seemed to be the result of using jQuery UI 1.7+ and one line inparticular within the CSS:

.ui-widget :active { outline: none; }

After removing the above line from the jQuery UI CSS the delay when clicking within jqGrid was instantly removed.

Share