Posts Tagged ‘javascript’

Removing All Spaces From a String Using Javascript

Posted in Javascript / jQuery, Web Development on October 20th, 2010 by Steve Marks – Be the first to comment

I recently wrote about how to remove all occurences of a character from a string using JavaScript by combining the replace() function and a regular expression. This works great but a problem arises when we use this method to try and replace all occurrences of a space.

Using the previously described method you might think we would do something like so:

var str = "B I O S T A L L"
str = str.replace(/ /g,'');
// Outputs 'B I O S T A L L'

By doing this however your string will remain unchanged and those pesky spaces still included. Instead, we need to use regular expressions again and look for the spaces using ‘\s’. Our code should therefore look like this:

var str = "B I O S T A L L"
str = str.replace(/\s/g,'');
// Outputs 'BIOSTALL'

So there we have it; all spaces stripped from the string. Remember that you could also replace the spaces with another character by changing the second parameter of the replace() function. Let me give you a quick example:

var str = "B I O S T A L L"
str = str.replace(/\s/g,'-');
// Outputs 'B-I-O-S-T-A-L-L'

Share

Passing an Optional Variable to a JavaScript Function

Posted in Javascript / jQuery, Web Development on October 13th, 2010 by Steve Marks – Be the first to comment

Ever needed to call a function expecting parameters but use the functions default value rather than passing the same value each time? Let me give you an example:

function do_something(my_var) {
	alert(my_var);
}
do_something();

In doing the above you will get ‘undefined’ output. So how do we assign the ‘my_var’ to a value if it’s not supplied?

The Solution

function do_something(my_var) {
	my_var = my_var || 'You did it!';
	alert(my_var);
}
do_something();

All we’re doing here is checking if the variable is undefined or not. If it’s been supplied as a parameter then use it, else assign it to a default value.

Share

JavaScripts replace() Function Only Replacing First Occurrence

Posted in Web Development on October 3rd, 2010 by Steve Marks – 1 Comment

The replace() function in JavaScript is useful for finding a substring within a string and replacing it with a new substring. What the official JavaScript documentation doesn’t state very clearly however is that the function will only replace the first occurrence. But what if we need to perform a global find and replace and swap out all occurrences?

The Solution

To swap out all cases of a substring we need to use a regular expression and add the identifier ‘g’ to end of the substring that we are looking for. For example:

var str = "This is sample text for a sample replace";
str = str.replace(/sample/g, "lovely");
alert(str);

You should be returned with ‘This is lovely text for a lovely replace’. Note how there are no quotes used around the substring parameter. Instead the substring is contained with forward slashes and the ‘g’ regular expression indentifier prepended to the end.

Share

Get a Page URL with JavaScript

Posted in Javascript / jQuery, Web Development on September 28th, 2010 by Steve Marks – Be the first to comment

Need to get the URL of a webpage using JavaScript? Simply use the code below:

var page_url = window.location.href;
alert(page_url);

View a Demonstration

Share

Reasons Why a HTML Form Might Not Submit

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

I’ve had it lots of times throughout my career; you build a form and it will not submit. I know how frustrating this can be so I’m going to outline a few reasons why this might be below:

1. Check your HTML Structure

In order for a standard HTML form to submit successfully it requires an opening and closing <form> tag and a submit button placed within these tags. Once you have confirmed this it is important to ensure that your form does not fall within or overlap another form on the page. Also, it might seem a bit obvious, but just check that your button is of type ‘submit’ or ‘image’. A standard input of type ‘button’ will not perform any actions on it’s own.

2. JavaScript Validation Errors

If you’re using JavaScript validation on the form it could be that your page is encountering script errors. Firefox’s Error Console is a great little tool for debugging these errors should this be the case. It is also important to note that if you are using JavaScript validation, be sure to add ‘return true’ if the users input passes validation.

3. Submitting the Form with JavaScript

This has caused me hours of grief this one. You’re submitting the form using the document.myform.submit() method and nothing happens right? This is more than likely due to the fact another component in your form shares the name ‘submit’. This is a reserved Javascript word so simply change the input in question to get around this.

I’m sure there a few other scenarios which might result in a form not operating as expected and I’ll add these as I think of them. Suggestions welcome via the comments below :)

Share

Foreign Characters in Javascript Alert Showing Question Mark In Diamond

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

You include a foreign character, for example à è ç ü, to a Javascript alert popup and it comes out as a question mark in a black diamond as follows:

Foreign Characters being shown as black diamond

Does this sound familiar? If so, I know how frustrating this can be because it took me hours to find a way to resolve this.

The problem is that the characters in question do not fall within the encoding of your webpage set via the meta ‘Content-Type’ tag. For example, a webpage using the UTF-8 character set will not display these characters correctly.

The Solution

Lets imagine we are trying to alert Tämä Rocks (Finnish for ‘This Rocks’), if we were to alert it straight out as below we would get the issue:

alert("Tämä Rocks")

Instead, we need to use the hexadecimal equivalent prepended by ‘\x’ to get the characters to appear correctly as follows:

alert("T\xE4m\xE4 Rocks")

In doing this we now get the expected results:

For a full list of hexadecimal conversions visit http://ascii.cl/htmlcodes.htm.

Share

Swap and Re-Order Divs Smoothly Using jQuery – Swapsies Plugin

Posted in Javascript / jQuery, Web Development on July 9th, 2010 by Steve Marks – 6 Comments

Swapping Two Divs Smoothly with jQuery

Well, it’s about time but I’ve finally taken the plunge and wrote my first jQuery plugin. I’ll admit, the decision wasn’t voluntary but a scenario on a recent project required a specific function that I couldn’t find had been previously catered for so I decided to kill two birds with one stone; complete the project and learn about the construction of jQuery plugins whilst putting it online for other people to use should they find themselves in a similar situation.

The requirement was to be able to swap two divs smoothly. Not just swap the contents of the divs in question, that was too easy, but to physically move the divs. One div to where the second div was positioned and vice versa, making the animation visible to the user to emphasise the movement.

After reading a few tutorials and a bit of debugging I had done it. The results of which can be seen below:

View a Demonstration

Installation

If you’d like to incorporate the Swapsies plugin into your own site, I have included a simple step-by-step below on how to do so:

1) Download the jQuery library here

2) Download the Swapsies plugin here

3) Include the scripts in your HTML like so, changing the paths to match where the JS files are located:

<script src="/js/jquery.js" type="text/javascript"></script>
<script src="/js/jquery-swapsies.js" type="text/javascript"></script>

4) Create the two divs you would like to swap, plus a trigger that will activate the swapping animation:

<div id="div_1">THIS IS DIV 1</div>
<div id="div_2">THIS IS DIV 2</div>
<a href="javascript://" class="go-swap">Go Swap!</a>

The HTML explained:

Div 1 (#div_1) – The first div on our page. This is one of the divs that will be swapped
Div 2 (#div_2) – The second div on our page. The other div that will be swapped
The trigger (.go-swap) – When clicked the swapping will commence. In our case this is a link but can be an image, a button or anything else you desire.

5) The final Javascript to bring our page to life:

$(document).ready(function() {
    $(".go-swap").click(function() {
        $("#div_1").swap({
            target: "div_2", // Mandatory. The ID of the element we want to swap with
            opacity: "0.5", // Optional. If set will give the swapping elements a translucent effect while in motion
            speed: 1000, // Optional. The time taken in milliseconds for the animation to occur
            callback: function() { // Optional. Callback function once the swap is complete
                alert("Swap Complete");
            }
        });
    });
});

Well there we have it. I hope that wasn’t too painful for you. If you have any questions with regards to integrating it into your site or have any suggestions on how the plugin could be improved simply leave a comment below.

Share

Using jQuery’s jCarousel Lite and Thickbox in Harmony

Posted in Javascript / jQuery, Web Development on July 7th, 2010 by Steve Marks – Be the first to comment

Using jCarousel Lite and Thickbox Together

There are two jQuery plugins that I probably use more than any others. These are jCarousel Lite by Ganeshji Marwaha and Thickbox by Cody Lindley.

jCarousel Lite – This plugin allows you to navigate images and/or HTML in a carousel-style widget.

Thickbox – Designed to show a single image, multiple images, inline content, iframed content, or content served through AJAX in a hybrid modal.

You do run into a problem however when you need to use both at the same time. Imagine you have a carousel of images that when clicked, you want to open in a Thickbox. This will work for the items initially in view when the page loads but as soon as you scroll left or right on the carousel, the newly visible images/HTML will not be linked to the Thickbox and will simply open up in full view.

The Solution
The problem here is that the Thickbox is initialized upon the page loading and associates itself with any links that have a class of ‘thickbox’. When jCarousel Lite does it’s magic, it’s essentially duplicating elements, that of which do not have a link with the Thickbox.

To get round this issue we need to tell Thickbox to re-look at what it should be looking for by using the jCarousel Lite option ‘afterEnd’. This allows us to perform an action everytime any activity occurs such as scrolling left or right.

See the example below on how best to achieve this:

<script type="text/javascript">
    $(document).ready(function() {
        $("#image-carousel").jCarouselLite({
            visible: 3,
            afterEnd: function(a) {
                tb_init('a.thickbox, area.thickbox, input.thickbox');
            }
});
</script>

Notice how we’re calling Thickboxes tb_init() function after every animation? This is the same function that is called by the Thickbox plugin when the page loads and allows us to re-assign all the elements on the page, including the ones that come into view as a result of scrolling the carousel.

Share

CodeIgniter Google Maps V3 API Library

Posted in Javascript / jQuery, PHP, Web Development on July 2nd, 2010 by Steve Marks – 124 Comments

CodeIgniter Library - Google Maps API

In early May 2010 I wrote a Google Maps API library for CodeIgniter. This used Version 2 of the Google API and was pretty limited.

Well, I’ve been working tirelessly over the past weeks to get a new version wrote that uses Version 3 of the API instead and I am very pleased to announce that it is now avalaible for download.

The library enables you to create a map and overlay multiple markers, polylines, polygons, rectangles, ground overlays and/or circles, all of which are fully customisable. The library also supports showing directions between two points, including the ability to show the textual directions alongside the map too, and marker clustering. The first stages of integration with the Google Places API are available for use too.

To get a copy, read the documentation or to view a demo simply follow the links below:

Download Library (Last updated 27th October 2011)

View GitHub Repository

View Documentation PDF (185kb)

View Demonstrations

The demonstrations above are basic examples of what can be achieved by using the library. I recommend you read the documentation to view a full list of configurable options.

An Introduction to using the Library (Watch on YouTube)

Library Features

  • Change the maps appearance including zoom, central position, size and control positioning.
  • Add multiple markers, ground overlays, circles, rectangles, polylines and polygons. Add them all on the same map, each with a whole host of configurable options to change the appearance and how they function.
  • Add event handlers to all items on the map. This means you can perform a custom action when, for example, a marker is dragged, or the map is clicked.
  • Too many markers? Enable marker clustering to speed up and clean up your map.
  • Geocode lookups. You don’t need to know the exact lat/long co-ordinates to center the map or add a marker. You can use a building name, an address, an area, in fact any textual location will work.
  • Javascript minimisation. Include the Jsmin.php file and minify the JS output by the library.
  • Either output the Javascript to the page or write it to a separate .js file.
  • Drawing Manager library integration
  • Add traffic, bicycling and Panoramio overlays.
  • Add directions by specifying a start and end point, as well as having the option to output the textual directions to a separate element on the page.
  • Caching of Geocode requests. Speed up the map by caching any geocode lookups made.
  • Integration with the Google Places API.
  • Support for HTML5 geocoding meaning you can center the map on a user’s location.
  • Support for use within an application using HTTPS
  • Allows you to integrate with your Google Adsense account and overlay ads on top of the map.

Upcoming Features

  • Support for KML and GeoRSS Layers
  • Support for creating multiple maps on the same page
  • Viewport Marker Management
  • Extensions to the directions integration
  • Extensions to the Google Places API integration
  • Possible integration with the Elevation API

If you have any questions, spot a bug, have any feature suggestions or would like to leave feedback please leave a comment below or drop me a line.

There is a lot of functionality to be added to this library soon so keep checking back for any progress or follow me on GitHub.

Share

When JW Player Doesn’t Play On IE

Posted in Flash, Javascript / jQuery, Web Development on June 22nd, 2010 by Steve Marks – 2 Comments

When JW Player Doesn't Play in IE

I’ve used the JW Player flash player for lots of projects now. It’s free, customisable enough and has a lot of documentation, plus community support, to help when something isn’t working right.

I ran into an issue during my latest project however where JW Player was working fine in Firefox but on Internet Explorer I was getting a blank area where the video should have been appearing.

The Solution
It turned out the path to my swfobject.js was not valid. I was previously using:

<script src='/js/swfobject.js' type='text/javascript'></script>

In order to get the player to work in all browers I needed to change my code to either:

<script src='js/swfobject.js' type='text/javascript'></script>

Or:

<script src='http://www.mydomain.com/js/swfobject.js' type='text/javascript'></script>

See how the path to ‘swfobject.js’ is either relative or absolute, rather than referring to the root? After making the above amendments it worked perfectly across all browsers.

Share