Skip to content Skip to sidebar Skip to footer

Perform Href Before Onclick

I've the following link: I And this use the following javascript: function showGallery(){ if(window.location.hash) {

Solution 1:

For modern browsers, you can bind your Javascript code to the onhashchange event. Links will be without Javascript:

<ahref="#HDR">I</a>

And the Javascript is run whenever the hash has changed:

functionlocationHashChanged() {
    if (location.hash === "#HDR") {
        $('#gallery').fadeIn('fast');
    }
}

window.onhashchange = locationHashChanged;

Solution 2:

Have you tried a setTimeout call to delay the onclick event?

Like this:

<ahref="#HDR"onClick="setTimeout(function(){showGallery.call(this)},20)">I</a>

Solution 3:

You can simplify this quite considerably, it is not good practice to use the href for other things than pure navigation.

<aonClick="showGallery('HDR')">I</a>

And then:

function showGallery(name){
    if(name) {
        $('#gallery').fadeIn('fast');
        alert(name);
    } else {

    }
}

Solution 4:

If you want to run showGallery() without following the link, the correct code is this:

<ahref="#HDR"onClick="showGallery(); return false;">I</a>

By keeping the href the user still sees the destination in the status bar and navigation still works for clients without Javascript (i.e. Google). By returning false in the event handler, you prevent the browser from following the link.

In showGallery(), you can then show the gallery and add '#HDR' to the location.hash.

Solution 5:

You don't need to verify the window's hash, because on first click you don't have any hash in the address bar. The functionality will only apply on the second click.

What you can do is this:

<a href="#HDR" id="g1" onClick="showGallery('g1')">gallery 1</a>

functionshowGallery(galid){
    var linkhash = $('#' + galid).attr('href').substring(1);

    alert(linkhash);

    $('#gallery' + linkhash).fadeIn('fast');
}

Post a Comment for "Perform Href Before Onclick"