user3598456
user3598456

Reputation: 13

When the url hash match a div's id then do something to the child of the div

Let's say I have the html as below:

<div class=".blog-item-holder">
<div id="AAAA"><div class="inner">AAAA</div></div>
<div id="BBBB"><div class="inner">BBBB</div></div>
<div id="CCCC"><div class="inner">CCCC</div></div> 
<div id="DDDD"><div class="inner">DDDD</div></div>
</div>

So reach of my url will be reset like this:

example.com/page/#AAAA
and
example.com/page/#BBBB
and
example.com/page/#CCCC
and
example.com/page/#DDDD

All I want is when people go to the page (for example: example.com/page/#BBBB) then the div#BBBB .inner will have a black back-ground, and same treatment for the url has has for CCCC, DDDD etc.

This is what I got so far on js:

if(window.location.hash) {
var hash = window.location.hash.substring(1),
    boxes = [];

$('.blog-item-holder > div').each(function(){
    if ($(this).attr('id') == hash) {
        $(this).children('div').css("background-color:#000000;");
    }
});
}

But somehow it doesn't seem to be working.

Upvotes: 1

Views: 1759

Answers (4)

BoltClock
BoltClock

Reputation: 724192

The :target pseudo-class is specifically designed for this sort of situation. No need to query window.location.hash using a script — the following CSS will be applied on-the-fly:

:target > .inner {
    background-color: #000000;
}

If you must use jQuery for compatibility with old browsers that don't support :target in CSS, you can still use it in a jQuery selector if you're using version 1.9 or later (see here for more details). Note that, as mentioned, the problem lies in your .css() argument so you need to fix that:

$(':target > .inner').css("background-color", "#000000");

Again, no need to query window.location.hash here, unless you need to use the hash fragment for other purposes. The entire if block can be replaced with this single statement.

Upvotes: 1

davo11122
davo11122

Reputation: 73

This must work :)

$(window).on('hashchange',function(){
  var _child = $(location.hash).children('.inner');
  _child.css('backgroundColor', '#000');
})

Upvotes: 0

Felix
Felix

Reputation: 38112

Try to use the correct syntax for .css():

$(this).children('div').css("background-color","#000000");

or:

$(this).children('div').css({"background-color":"#000000"});

instead of:

$(this).children('div').css("background-color:#000000;");

Upvotes: 3

sshet
sshet

Reputation: 1160

Here you are making mistake of assign css properties via Jquery, you need to assign properties using key , value in .css()

Try to debug what value you getting for hash first

if(window.location.hash) {
var hash = window.location.hash.substring(1),
    boxes = [];

$('.blog-item-holder').find('.inner').each(function(){
    if ($(this).parent().attr('id') == hash) {
        $(this).css("background-color","#000000");
    }
});
}

Upvotes: 0

Related Questions