Posts Tagged ‘javascript’

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

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

Disabling the Submit Button to Prevent Double Form Submission

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

Whether it be due to a users lack of tech know-how or a twitch of the finger, a secondary click of a forms ‘Submit’ button could result in the form being submitted twice. Depending on the action of the form this could in turn send two enquiries, create two orders or insert a record into the database twice.

To get around this we can use a very simple bit of Javascript to disable the ‘Submit’ button after the first click. Even if the user does end up clicking twice or more these additional clicks will not count.

A Demonstration

Below is a standard button. Go ahead, click it multiple times and you will see each click is received:

Now for our updated button that only allows one click by the user:

Ok, now that we’ve seen it in action lets look at how to implement this using Javascript.

The Code

Depending on how your form already works we can go about adding this feature one of two ways:

1) No form validation exists / Adding the code directly onto the button

If your form doesn’t contain any validation we can add the code directly to the button. The example button shown above uses the following code:

<input type="submit" name="Submit" value="Submit" onclick="this.disabled=true; this.value='Please Wait...';" />

2) Form validation already exists / Adding the code to a pre-existing function

If Javascript validation already exists on your form to check the users input it’s easier to update this function with your new code. I’ve included below an example of how this might look:

<script type="text/javascript">
    function validateForm(formObj) {

        if (formObj.username.value=='') {
            alert('Please enter a username');
            return false;
        }

        formObj.submitButton.disabled = true;
        formObj.submitButton.value = 'Please Wait...';
        return true;

    }
</script>

<form name="frmTest" action="" method="post" onsubmit="return validateForm(this);">
    Username: <input type="text" name="username" value="" /><br />
    <input type="submit" name="submitButton" value="Submit" />
</form>

If adding the disabling functionality to your button using the second method ensure that you place the new code after the validation takes place. If you place it before any of the checks your user will not be able to submit the form again should it fail validation.

Today we used the input tags ‘disabled’ attribute. You can view more information about this by following the link: www.w3schools.com/TAGS/att_input_disabled.asp

Share

Detect InfoWindow Being Closed – Google Maps V3 API

Posted in Javascript / jQuery, Web Development on November 2nd, 2010 by Steve Marks – 1 Comment

Detect Google Maps infowindow Being Closed

If you’re including a map on your website using the Google Maps V3 API there’s a high chance you’ll be including overlaid markers and infowindows that are related to these markers. Adding the markers is simple enough, as is getting the infowindows to open upon clicking them, but what if we need to detect when an infowindow is closed?

I came across this scenario earlier today where I need to set the map back to a certain lat/lon position upon the infowindow being closed. After a bit of research and playing around I figured it out to be something like so:

google.maps.event.addListener(infowindow, 'closeclick', function() {
	alert("I'm Closed");
});

Simply add the above to within the map initialisation function and you’ll now be able to perform actions upon infowindows being closed.

Note: You’ll need to change ‘infowindow’ in the above snippet to the variable name assigned to the infowindows in your own code.

Share

Remove the Scrollbar in Fullscreen Mode when Using JavaScript

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

By using the window.open() function of JavaScript we can popup a new browser window/tab, specify the height and width of the window to be opened, and even set whether to hide or show certain elements such as toolbars, the address bar and more.

One of the other attributes we can specify is whether or not the window opens in fullscreen mode. An example of this would be like so:

window.open('popup_url.html', 'newWindow', 'fullscreen=yes, scrollbars=no');

Simple enough really. We’ve set the URL of the window to be opened, the name of the new window, along with any attributes; in this case to open the window full screen and with no scrollbars.

I know what you’re saying: “But my popup still has scrollbars”

You’re absolutely right. When opening a new window in fullscreen the ‘scrollbars’ parameter is not taken into account and therefore we need to adjust the file contained within our popup (in the above case popup_url.html). Simply add the following to the opening <body> tag:

<body style="overflow:auto">

Or:

<body style="overflow:hidden">

In doing the above the scrollbars should be now gone (or at least only shown if required).

Share