Javascript / jQuery

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

How to Check if jQuery’s ColorBox is Open or Closed

Posted in Javascript / jQuery, Web Development on October 20th, 2010 by Steve Marks – 1 Comment

Get jQuery Colorbox State

jQuery’s ColorBox is one of my favourite and most used jQuery plugins. It’s simple to set up, looks great, very customisable and the website contains examples to cover every scenario you could imagine.

One thing that I couldn’t achieve right away however was how to get the current state of the ColorBox at any one time. Was it open? Was it closed? After a bit of playing around I discovered that the plugin creates an element with an ID of ‘colorbox’. By using this, combined with jQuery, I could then easily detect the current state by doing something like so:

if ($("#colorbox").css("display")=="block") {
	alert('ColorBox is currently open');
}else{
	alert('ColorBox is currently closed');
}

So there we have it. Simple huh? An another alternative is that you use the callback functionality of ColorBox and update a global JavaScript variable each time it is opened and closed, but I’ll save that for another day…

Share

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

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