Dotan
Dotan

Reputation: 7622

jquery event on hashed div

I have a page with a lot of divs, and I want to direct users to a certain div using #DIV_NAME and highlight that div.

I tried it with JQUERY

    var hasih = window.location.hash.substring(1);
    $('div#'+hasih).addClass("div_highlight");

and it works only if I load the page once, then refresh.

how can I make it work on the first time the page is loaded?

tnx

Upvotes: 0

Views: 181

Answers (3)

yckart
yckart

Reputation: 33408

$(window).bind('load hashchange', function() {
    var hasih = window.location.hash.substring(1);
    $('div').removeClass('div_highlight');
    $('div#' + hasih).addClass("div_highlight");
});

Just switch the url between

http://jsfiddle.net/KWTmm/show/#hash1

http://jsfiddle.net/KWTmm/show/#hash2

Upvotes: 0

CronosS
CronosS

Reputation: 3159

As a side note, you can achieve this effect in css-only, without javascript.

CSS 3 introduces the new :target pseudo-classe [more info].

The :target pseudo selector in CSS matches when the hash in the URL and the id of an element are the same.

Here is a simple example (demo js fiddle):

HTML

<a href="#first">first</a> - <a href="#second">second</a> - <a href="#third">third</a>

<div id="first"></div>
<div id="second"></div>
<div id="third"></div>​

CSS

div{
    height: 50px;
    width: 50px;
    border: 1px solid black;            
}

div:target{
    border-color: red;
}

Upvotes: 1

ygssoni
ygssoni

Reputation: 7349

You can do it like this :

$('a').click(function(){
    var selector = $(this).attr('href');        
    $('html').animate({
        scrollTop: $(selector).offset().top
    }, 500,'',function(){
        $(selector).effect("highlight", {}, 1000);                             
    });
    return false;
});

Here is the demo

Dont forget to include jQuery UI

Upvotes: 0

Related Questions