I am trying to trigger a button click on pageload with the piece of jQuery below
<script> jQuery(function(){ jQuery('#clickson').click(); }); </script>
It works perfectly but I have this button id on every page, how can I use it such that it only triggers on homepage and subdomain homepages.
For example it should only fire on example.com, subdomain1.example.com, subdomain2.example.com and NOT on any other pages like example.com/path, subdomain1.example.com/path, subdomain2.example.com/path
Try checking location.href
for selected url
jQuery(function() {
var loc = location.href;
// if `location.href` is equal to
// "example.com","subdomain1.example.com", "subdomain2.example.com"
// call `.click()` on `#clickson`
if (loc === "example.com"
|| loc === "subdomain1.example.com"
|| loc === "subdomain2.example.com") {
jQuery("#clickson").click();
}
});
jQuery(function() { if (location.href === "http://stacksnippets.net/js") { jQuery("#clickson")[0].click(); } });
#home { display:block; position:relative; top:400px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <a id="clickson" href="#home">click</a> <div id="home">home</div>
Since you said you were against hardcoded string approaches, heres a simple bit of code that will accept an array of pages. location.pathname
is the section of the url coming after the domain and before the query string. to my knowledge, it is implemented in every browser i have ever encountered.
var pages=['/','/home'];
for(var i=0;i<pages.length;i++)
{
if(location.pathname==pages[i])
{
//do stuff you want here
break; //terminates the loop on first match
}
}
Use regex to match currect URL:
var href = window.location.href;
var regex = /(example\.com)$/i; // find only example.com at the end of URL
if ( regex.test(href) ){
// if passed
// do jQuery stuff here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.