jQuery target $(window) on a specific webpage
I'm just wondering if there is any easy way i can target $(window) to only work on localhost/website/hello and not localhost/website/bye
I've made a easy test script,
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
alert('Hello World');
}
});
The problem is that this snippet will work on all pages where the开发者_运维知识库 script is loaded...
Use location.href
value to check what page your are loading.
if (location.href == "your_page") {
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
alert('Hello World');
}
});
}
To match a set of different pages use Regular Expressions.
Live Demo
var currentPage = window.location.href.match(/website\/(.*)/)[1];
if(currentPage === 'hello/'){
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
alert('Hello World');
}
});
}
so basically anything after website/
will be matched.
Check the page path name first and then apply a condition
var url = location.pathname;
if ("url:contains('localhost/website/hello')") {
if ($(window).scrollTop() == $(document).height() - $(window).height()){
alert('Hello World');
}
}
else ("url:contains('localhost/website/bye')") {
//do something else
}
if( window.location.hostname.indexOf("localhost") != -1 ) {
alert('on localhost');
}
if( window.location.pathname.indexOf("hello") != -1 ) {
alert('path contains "hello"');
}
you can use the window.location object to parse the url and check against specific parts.
精彩评论