tag (jquery)

archive

extracting key value pairs of an array in javascript with jquery Jan
06
1
1

At times I feel spoiled using Python, especially when I try to do what seems to be a trivial operation to discover there's not already a construct to do it in whatever language I'm in at the time. One of these instances is when I try to loop over and extract key value pairs out of an array in Javascript. Being in the Python mode I'm usually hoping to find something like the following:

# python
for key, value in array:
    ....

The best I could come up with is to use the each() function from JQuery to loop over each element.

var example = {};

example['apple'] = 1;
example['orange'] = 2;

$.each(example, function(key, value) {
    console.log(key);
    console.log(value);
});

Or, for a non-jquery solution:

for(var key in example) {
    console.log(key);
    console.log(example[key]);
}

comments

detect and change html named anchor tags in the url through javascript and jquery Oct
06
1
0

You may already be familiar with using html named anchor tags to auto-scroll the page to a certain section in an html page, which would look something like this:

<a id="button" href="#tag">link</a>

...

<a name="tag">anchor</a>

An alternative use for anchor tags is to change and detect the tag value in the url on the fly in order to initialize certain states with javascript-driven content. This is handy as it lets people bookmark the location and the page will initialize properly even in heavy ajax environments. It's surprisingly easy to interact dynamically with the url anchor tag object.

You can detect the current anchor value of the url in javascript through "location.hash" like this:

if(location.hash == '#tag') {
    // initialize content
    ...
}

You can also dynamically change the anchor tag in the url just by setting "location.hash" like so:

// location.hash = 'value';

$('a#button').click(function(event) {
    event.preventDefault();

    // set the anchor value
    // I like to strip the hash out of the href value; you can use your own method of choice to determine the anchor.
    location.hash = $(this).attr('href').replace('#', '');

    // do something important
    ...
});

These examples use JQuery to simplify the code.

comments

fixing jquery ajax caching Jun
16
1
0

Depending on browser settings you might run into problems with caching when calling pages through AJAX. I've run into issues with WebKit based browsers (Chrome, Safari) as it seems they are more aggressive with their caching than Firefox and even IE. This was one of the few times where something worked in IE and not Safari.

If your ajax is calling a dynamically generated page where its content changes over time you need to disable caching on the AJAX call.

In JQuery you can just set the cache parameter to false:

$.ajax({
  url: "/path/to/page/",
  type: "POST",
  cache: false,
  success: function(data){
    ...
  }
});

Another technique that you can do is to generate a random variable on each call to the end of URL to trick the browser.

$.ajax({
  url: "/path/to/page/?v=" Math.ceil(10000*Math.random()),
  type: "POST",
  success: function(data){
    ...
  }
});

comments

limit character entry with jquery May
18
1
0

It's common to need to limit character count on user input fields. There's a lot of plugins that you can get this to do it for you. However, when possible I like to reduce the amount of third party scripts. The basic concept is pretty simple to follow in JQuery.

Lets say you have HTML like the following:

<div id="limit"></div>

...
<textarea name="comment" cols="40" rows="10" id="comment"></textarea>
...

You can then bind a keypress event that checks the lengh of the value on the input or textarea.

$('#comment').keypress(function() {
    var MAX_CHAR = 140 - 1;

    $('#limit').text('Characters remaining: ' + ((MAX_CHAR + 1) - $(this).attr('value').length));

    // limit entry
    if($(this).attr('value').length > MAX_CHAR) {
        this.value = this.value.substring(0, MAX_CHAR);
    }
});

This script prints out how many characters are left in the <div id="limit"> and limits the user to inputing 140 characters. No plugins necessary.

Limiting input on the front end is only a convenience for the user. If this functionality is important for your application make sure to make the proper checks and sensitization on the backend when processing the form.

comments

a simple accordion menu with jquery Apr
20
1
0

I've seen a lot of bloated scripts trying to attach an accordion effect onto a nested menu that just end up being slow, buggy, complicated, and hard to extend. I think people are over thinking things . If you're using JQuery it's easy enough to write this functionality yourself.

working example

Lets say your HTML looks something like this:

<ul id="accordion">
    <li>
        <h1>First</h1>
        <ul>
            <li><a href="#">section</a></li>
            <li><a href="#">section</a></li>
            <li><a href="#">section</a></li>
        </ul>
    </li>

    <li>
        <h1>Second</h1>
        <ul>
            <li><a href="#">section</a></li>
            <li><a href="#">section</a></li>
            <li><a href="#">section</a></li>
        </ul>
    </li>

    <li>
        <h1>Third</h1>
        <ul>
            <li><a href="#">section</a></li>
            <li><a href="#">section</a></li>
            <li><a href="#">section</a></li>
        </ul>
    </li>
</ul>

You can easily initialise and attach the accordion functions like so:

$(document).ready(function() {
    // initialise
    $('ul#accordion > li > ul').hide();
    $('ul#accordion > li:first-child > ul').show();

    // accordion
    $('ul#accordion > li > h1').click(function() {
        // do nothing if already expanded
        if($(this).next().css('display') == 'none') {
            $('ul#accordion > li > ul').slideUp();
            $(this).next().slideDown();
        }
    });
});

I hope you find this code simple and easy to extend.

comments

create xhtml strict external links with jquery Mar
15
1
0

If you're anything like me when coding to the XHTML strict doctype, you get annoyed when things break your validation (Youtube, I'm looking at you). I've seen many a flame war over whether or not to let external links open a new window. It's not my intention to rekindle the flames, so lets just say this: Sometimes you just have to do what the client wants. Besides, who am I to argue? After all it's their site that they are paying me to build.

With that being said, now comes the question about how to allow links to open a new window without breaking your strict validation with the deprecated target="_blank" attribute. I've found that auto-detecting the link with jquery has been a fairly elegant and painless solution.

At this point it's worth noting that the target attribute will no longer be deprecated in HTML5, so our good friend target="_blank" will be back. But until HTML5 is better supported (cough Microsoft) we're going to be stuck with alternate solutions; so let us tarry forth.

The first thing I do is to organize my site so that all internal links are relative, and external links are absolute (starts with http://). With that in place I can then open a new window whenever I detect an href that contains http://.

$('a[href^="http://"]').click(function(event) {
    return !window.open(this.href);
});

That's a nice start, but there are rare occasions where I'd like to open a new window for an internal link, and keep an external link in the same window. For these outliers I override the script by adding a rel="internal" or rel="external" into the <a> tag and handle it with the javascript. So the complete script looks like this:

$(document).ready( function() {
$('a[href^="http://"]').click(function(event) {
if($(this).attr('rel') != 'internal') {
return !window.open(this.href);
}
});

$("a[rel='external']").click(function() {
return !window.open(this.href);
});
});

<a href="/page">stays in the same window</a>
<a href="http://example.com">opens a new window</a>
<a href="/page" rel="external">opens a new window</a>
<a href="http://example.com" rel="internal">stays in the same window</a>

And this will cover 99% of my needs.

comments