Reputation: 23969
I want to trigger a click on a div on page load, but which div depends on the url.
E.g. HTML
<div id="1" class="clickMe"></div>
<div id="2" class="clickMe"></div>
<div id="3" class="clickMe"></div>
<div id="4" class="clickMe"></div>
A page URL might be:
http://this-site.com/pageName?thing=2
On this occasion I would want to trigger a click on div with class clickMe
, with id=2
I know I can use $( ".clickMe" ).trigger( "click" );
but is there a way to select the div clickMe
that I want?
Upvotes: 0
Views: 1108
Reputation: 68
I know how to get URL variables into JS
Then store that in a variable called "thing" and
$( "#" + thing ).trigger( "click" );
Upvotes: 2
Reputation: 24406
You want to first of all get the thing
variable from the query string into jQuery, then specify it as the correct ID selector to trigger a click on. I'm going to copy a function used in the article that Phil flagged this post as a duplicate of:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var thing_id = getParameterByName('thing');
$( ".clickMe#" + thing_id ).trigger( "click" );
You can specify a class and an ID like this: $('.className#IDname')
, however ID's should always be unique in a web page, so you shouldn't actually need to do that. This should suffice:
$('#' + thing_id).trigger('click');
Upvotes: 1