PlayerWet February 2016

A selector switch id with jquery as condition

perhaps too easy what I ask, or maybe not. Anyway, I need to call a certain anchor of the page as the link is pressed, it enters a particular URL with a particular Anchor scroll down to that anchor.

I'm doing it with jquery like this:

$(document).ready(function() {

    var anchor = window.location.hash.substring(1);

    if(anchor!="") {

        var newAnchor= "'#anchor-" +anchor+"'";

        $(newAnchor).trigger("click");

    }

});     

I think this is not possible be, I certainly have never seen it, I get the following error:

Uncaught Error: Syntax error, unrecognized expression: '#anchor-2015'

Is it possible to call a selector dynamically like this? Was there another way?

Thank you.

Answers


Igor February 2016

Remove single quotes, they are not needed.

var newAnchor= "#ancla-" + anchor;


Mati Tucci February 2016

Yes it's possible. You have wrong the quotes.

$(document).ready(function() {

    var anchor = window.location.hash.substring(1);


if(anchor!=""){

    var newAnchor= "#anchor-" + anchor;

    $(newAnchor).trigger("click");


    }


}); 

Post Status

Asked in February 2016
Viewed 2,531 times
Voted 8
Answered 2 times

Search




Leave an answer