Posts Tagged ‘jquery’

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

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

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

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

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

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

Simple AJAX / PHP Enquiry Form Tutorial

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

During my 7 or so years of working with PHP I have created literally 100′s of enquiry forms. From simple ones containing just a couple of fields to complex ones (sometimes maybe a bit too complex) containing hundreds of different variables. They all essentially however do the same thing; The user enters their details and clicks a submit button, the information is validated and emailed to a specified email address and the user is presented with a success message thanking them for their enquiry.

Don’t get me wrong, this method works absolutely fine, but what with the increasing popularity of AJAX over the past few years I decided to spruce things up a bit with my most recent form creations. By using AJAX to submit my forms I could seamlessly gather the user input and send the email without refreshing the whole page. The end result being a much smoother and user-friendly process.

Based on what I’ve learnt in doing this I’m going to show you how to create a very basic enquiry form using a combination of AJAX, PHP and the Javascript library jQuery. I use jQuery to deal with the AJAX functionality in a simple manner but you could use another Javascript framework or even try to deal with this manually.

Step 1
Create a new file called ‘enquiry_form.html’ and place the below code into it:

<html>
<head>
    <title>My Enquiry Form</title>
    <script src="jquery.js" language="javascript" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        function send_enquiry() {
            $.post("process_enquiry.php", $("#frmEnquiry").serialize(),
                function(returnData){
                    if (returnData=="success") {
                        $("#enquiry-form").html("Thank you. Your enquiry has been sent successfully");
                    }else{
                        alert("An error occured whilst trying to send your enquiry. Please try again shortly\n\n"+returnData);
                    }
                }
            );
        }
    </script>
</head>

<body>

<div id="enquiry-form">
    <form id="frmEnquiry">
        <table>
            <tr>
                <td>Name</td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td>Enquiry</td>
                <td><textarea name="enquiry"></textarea></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="button" name="send" value="Send Enquiry" onclick="send_enquiry()" /></td>
            </tr>
        </table>
    </form>
</div>

</body>
</html>

At the top of the code we are including the jQuery library and the Javascript that will send the users input to a separate file, process_enquiry.php, that we will create in Step 2. In this Javascript we also deal with the outcome of sending the email; If successful remove the enquiry form and display a success message or alternatively, output an error message if for some reason the email could not be sent.

The code above also generates a simple form containing two fields, ‘Name’ and ‘Enquiry’ and should look like the below image:

Simple AJAX/PHP Enquiry Form Step 1

Step 2
Now that we have our form we need a PHP script to actually send the email that contains the user’s details. To do so, create another new file called ‘process_enquiry.php’ and copy the below code into it:

<?php

$to = "your@address.com";

$subject = "Enquiry Received";

$body = "A new enquiry has been received:\n\n";
$body .= "Name:\n".$_POST['name']."\n\n";
$body .= "Enquiry:\n".$_POST['enquiry'];

mail($to, $subject, $body);

echo 'success';

?>

Simply change the email address on line 3 to your own address, upload the three files to a webserver (enquiry_form.html, process_enquiry.php and jquery.js) and you’ve just finished creating a very simple AJAX enquiry form. Go on, give it a go. With any luck once you click ‘Send Enquiry’, the form should disappear and present you with a message and an email should drop into your inbox containing the information you entered.

Please note, this tutorial has shown how to create an AJAX enquiry form in it’s most simplest format to show the core processes involved. In order to maintain simplicity and focus on the key elements there has been no validation or security efforts put into the code provided. Adding these once you have the code working is highly recommended.

Share

Detect Leaving Visitors with jQuery

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

Users leaving your website is never a good thing, but there are some scenarios where you may need to catch them before they head elsewhere on the web as a result of them clicking a link on your site.

Let’s imagine that you want to bring to the users attention the fact they are leaving your website and that you are not responsible for the content of the site they are heading to. This may be particularly useful for websites belonging to legal or pharmaceutical companies, or for sites that display user-submitted URL’s such as directories.

By using jQuery we can quickly and easily detect this scenario. Simply copy and paste the code below anywhere on a page for it to work:

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

<script type="text/javascript">

	// Change this URL to be that of your own website
	var base_url = "http://www.yourdomain.com/";
	var base_url_length = base_url.length;

	$(document).ready(function() {

		$("a").click(function() {

			var link_location = $(this).attr('href');

			// if the link clicked is external
			if (link_location.indexOf("http://")!=-1 && link_location.substr(0, base_url_length)!=base_url) {

				/* DO ACTION HERE */
				alert("You are leaving the website");

			}

		});

	});

</script>

Please note, this script does not detect if a user closes the window or leaves your site by another means, such as by going direct to another website by typing it’s URL in the address bar.

Share

Open jQuery Colorbox onLoad

Posted in Javascript / jQuery, Web Development on April 7th, 2010 by Steve Marks – 24 Comments

Open a jQuery colorbox with no user interaction

Update – 26th December 2010 (Credit to azrad)

Since writing this post it seems that ColorBox has been updated meaning the solution below is now longer needed. Simply using the latest version of colorbox will allow you to open the ColorBox onLoad.


I came across a scenario today where I needed to open the jQuery ColorBox as soon as the page loaded. After looking on the ColorBox website it read as follows:

And it can be called directly, without assignment to an element
Example: $.fn.colorbox({href:”thankyou.html”});

After attempting to add the above code to the onload event of the page nothing happened. No ColorBox, no errors, nothing. After a short while spent researching it appears that there is an extra parameter required called ‘open’ that, if set to TRUE, results in the ColorBox opening automatically with no input from the user. The resulting, and functioning, code now looked as follows:

<script type="text/javascript">
	$(document).ready(function() {
		$.fn.colorbox({href:"thankyou.html", open:true});
	});
</script>

Share