Jquery if hash url click event / activate javascript

So, from the home page I have a link that goes to the product listing page. The product page has U / F divs.

I need the corresponding div to expand depending on which url #.

So, the link on the main page

<a href="/out-products.php#healthysnacks">healthy snacks</a>

when I click the link above, I try to activate it on the product page:

<a href="javascript:ReverseDisplay('products4')" id="healthysnacks"> Healthy Snacks</a>

I tried some of the other codes that I found that the trigger click while checking the hash tag and none of them worked properly, I think this is due to ReverseDisplay js. Please any help will help.

thank

+5
source share
3 answers

You can make the following changes to the document ready function on the product page:

: jQuery id-selector #elementId, window.location.hash id .

if ( window.location.hash ) {
    $(window.location.hash).click(); //clicks on element specified by hash
}

: , js .

$('#healthysnacks').click(function(e) {
    e.preventDefault();
    ReverseDisplay('products4');
});

, , $(window.location.hash).click() . , :

<a href="#" id="healthysnacks"> Healthy Snacks</a>
+6

hash Location, :

$(document).ready(function(){
   var id = window.location.hash;
   $(id).trigger('click')
})

jQuery javascript:, jQuery click:

$('#healthysnacks').click(function() {
   // do something here
})
+3

, ...

Use extreme caution when using window.location.hash, as in the jQuery selector, as this could lead to an XSS vulnerability. $ () can also create an HTML element and with a carefully crafted hash value, someone can execute arbitrary JavaScript code.

for instance

http://my-website.com/about#'><img src=x onerror=alert(/XSSed/)>

If my-websites.com/about- page uses window.location.hash inside the jQuery selector, then onerror code will eventually be executed.

+3
source

All Articles