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
}
Related
How do I hide a div on all posts except posts on category pages in WordPress?
I currently have the following jQuery but can't get it to work -
jQuery(function(){
if (window.location.pathname == "offonalim.com/category/fashion.html"||window.location.pathname == "offonalim.com/category/interior.html"||window.location.pathname == "offonalim.com/category/travel.html"||window.location.pathname == "offonalim.com/category/work.html") {
jQuery('.qodef-post-title').show();
jQuery('.qodef-post-info').show();
} else {
jQuery('.qodef-post-title').hide();
jQuery('.qodef-post-info').hide();
}
});
I can see that category pages of your website contains the keyword "Category" in each url,
so you can use this keyword to check if the url is having this particular keyword then show or hide divs accordingly
No need to specify full urls.
<script type="text/javascript">
function myFunction(){
val path=window.location.pathname;
if(window.location.href.indexOf("category") > -1) {
$('.qodef-post-title').show();
$('.qodef-post-info').show();
} else {
$('.qodef-post-title').hide();
$('.qodef-post-info').hide();
}
}
myFunction();
</script>
window.location.pathname yields the pathname, not the entire URL. So, your code is logically incorrect.
And instead of checking for each path individually, an ideal practice would be to create an array of possible paths and check the location's path in that array. Something like this should work fine:
var catPaths = [
"/category/fashion.html",
"/category/interior.html",
"/category/travel.html",
"/category/work.html"
];
jQuery(function() {
if (catPaths.includes(window.location.pathname)) {
jQuery('.qodef-post-title').show();
jQuery('.qodef-post-info').show();
} else {
jQuery('.qodef-post-title').hide();
jQuery('.qodef-post-info').hide();
}
});
You can further minimize the code by using toggle() and grouping the selectors:
jQuery(function() {
var includes = catPaths.includes(window.location.pathname);
jQuery('.qodef-post-title, .qodef-post-info').toggle(includes);
});
and really don't know much about jquery and I am already practicing, had some issue.
Question is that I have a url in the footer and I want if the url is not equal to hariskhan.com.pk then redirect it to something.com.
check my code:
$(document).ready(function(){
var check = $("a").attr('href');
var haris = "http://www.hariskhan.com.pk";
if (check == $("haris")) {
$("body").css("background", "green");
}
else {
$("body").css("background", "orange");
}
});
DOM:
<div class="footer"><a href="http://hariskhan.com.pk"/>
You are comparing a string to a jQuery object. So let's fix that first
$(document).ready(function(){
var check = $("a").attr('href');
var haris = "http://www.hariskhan.com.pk";
if (check == haris) {
...
}
});
Then you want to redirect the page
$(document).ready(function(){
var check = $("a").attr('href');
var haris = "http://www.hariskhan.com.pk";
if (check == haris) {
location.href = "//something.com";
}
else {
$("body").css("background", "orange");
}
});
well, first let's start by asking did you put the jquery code in a script tag??
did you create a proper html dom?
do you understand that you jquery code needs to select href from a tag?
you need to study html and understand a bit about how it integrates to javascripts before you start jquery
I am playing with jquery and js, trying to build an ajax overlay image viewer for a PHP website. With this code included at the bottom of the 'gallery page', the viewer opens and i can navigate with next and previous links inside the viewer. But the back button and the history is hard to understand. The browser often shows only the response of the ajax call, without the underlying page and css files, after some clicks back.
Perhaps somebody knows what is generally happening in such a case? I would like to understand why back sometimes results in a broken page, i.e. only the ajax response.
<script type="text/javascript">
$(document).ready(function() {
function loadOverlay(href) {
$.ajax({
url: href,
})
.done(function( data ) {
var theoverlay = $('#flvr_overlay');
theoverlay.html( data );
var zoompic = $('#zoompic');
zoompic.load(function() {
var nih = zoompic.prop('naturalHeight');
var photobox = $('#photobox');
if($(window).width() >= 750){
photobox.css('height',nih);
}
theoverlay.show();
$('body').css('overflow-y','hidden');
$(window).resize(function () {
var viewportWidth = $(window).width();
if (viewportWidth < 750) {
photobox.css('height','auto');
zoompic.removeClass('translatecenter');
}else{
photobox.css('height',nih);
zoompic.addClass('translatecenter');
}
});
});
});
return false;
}
var inithref = window.location.href;
$(window).on('popstate', function (e) {
if (e.originalEvent.state !== null) {
//load next/previous
loadOverlay(location.href);
} else {
//close overlay
$('#flvr_overlay').hide().empty();
$('body').css('overflow-y','scroll');
history.replaceState(null, inithref, inithref);
}
});
$(document).on('click', '.overlay', function () {
var href = $(this).attr('href');
history.pushState({}, href, href);
loadOverlay(href);
return false;
});
});
</script>
edit
clicking forward works:
/photos (normal page)
/photos/123 (overlay with '/photos' below)
/locations/x (normal page)
/photos/567 (overlay with '/locations/x' below)
clicking back gives me the broken view at point 2.
Do you need to prevent the default behaviour in your popstate to prevent the browser from actually navigating back to the previous page?
you have to manage it by own code.
You have a few options.
Use localstorage to remember the last query
Use cookies (but don't)
Use the hash as you tried with document.location.hash = "last search" to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request.
I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible
Changing to document.location.hash = "latest search" didn't change anything.t.
This goes into the rest of the jQuery code:
// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}
// Save the search result table when leaving the page.
$(window).unload(function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var form = $("#myTable").html();
localStorage.setItem('myTable', form);
}
});
Another solution is that use INPUT fields to preserved while using back button. So, I do like that :
My page contains an input hidden like that :
Once ajax content is dynamicaly loaded, I backup content into my hidden field before displaying it:
function loadAlaxContent()
{
var xmlRequest = $.ajax({
//prepare ajax request
// ...
}).done( function(htmlData) {
// save content
$('#bfCache').val( $('#bfCache').val() + htmlData);
// display it
displayAjaxContent(htmlData);
});
}
And last thing to do is to test the hidden field value at page loading. If it contains something, that because the back button has been used, so, we just have to display it.
jQuery(document).ready(function($) {
htmlData = $('#bfCache').val();
if(htmlData)
displayAjaxContent( htmlData );
});
I have a simple site, which slides the content off the page before taking you to the URL. However, I need to be able to determine the slide direction, depending on which page you're currently on.
I need to do this, but I'm not sure how to articulate it properly with jQuery:
if (current page == about.php) {
animate right then go to target URL }
else {
do default behaviour }
At the moment, I have this function which doesn't work well, because it animates in a certain way regardless of which URL you're going to:
function animateLeftAndGo(x) {
$(x).click(function (e) {
e.preventDefault();
var href = this.href;
$('.pop-up').fadeOut(function(){
$('.wrapper').animate({left: "+=150%"}, "slow", function(){
window.location = href;
});
});
});
}
Which is called by:
animateLeftAndGo('a.archive');
How can I set up an if statement that asks if the current URL is about.php?
In JavaScript use the location object: http://www.w3schools.com/jsref/obj_location.asp
if (location.pathname == '') {
}
I am trying to hide a div whenever someone goes to a specific url.
Something like this:
var url = document.location.href;
if (url.indexOf('http://donorperfect.local/asp/loginfull.asp') >= 0) {
$('#hidebox').hide();
} else {
$('#hidebox').show();
}
write("<div id=\"hidebox\">\n");
write("<p>test</p>\n");
write("</div>\n");
Run your code after the page is loaded and the element to hide is available to jQuery. Also convert the url into lower case and compare in case user types in mixed cases.
$(function(){
var url = document.location.href;
if (url.toLowerCase().indexOf('http://donorperfect.local/asp/loginfull.asp') >= 0) {
$('#hidebox').hide();
} else {
$('#hidebox').show();
}
});
EDIT
Going off of the link that you provided as an example, there are several issues here.
Your SCRIPT tag should be in the HEAD block
You are using $() when it is not available (Firebug gives a clear error on this)
The file name does not match your indexOf() match
Fixing these issues, it works fine. See:
<head>
...
<script language='JavaScript' src='/js/jquery-1.4.1.js' type="text/javascript"></script>
...
<script type="text/javascript">
$(function(){
var url = window.location.href;
if (url.indexOf('donorperfect.html') > -1) {
$('#hidebox').show();
} else {
$('#hidebox').hide();
}
});
</script>
...
</head>
http://jfcoder.com/test/donorperfect.html
The following code works (setTimeout is for demonstration purposes):
document.write("<div id=\"hidebox\">\n");
document.write("<p>test</p>\n");
document.write("</div>\n");
$(document).ready(function(){
var url = 'http://donorperfect.local/asp/loginfull.asp';
if (url.indexOf('http://donorperfect.local/asp/loginfull.asp') > -1) {
setTimeout(function(){$('#hidebox').hide()},2000);
} else {
$('#hidebox').show();
}
});
http://jsfiddle.net/userdude/Qt8uH/
Although this is probably what I would recommend (for instance, what happens if it's HTTPS?):
document.write("<div id=\"hidebox\">\n");
document.write("<p>test</p>\n");
document.write("</div>\n");
$(document).ready(function(){
var url = 'http://donorperfect.local/asp/loginfull.asp';
if (url.toLowerCase().indexOf('loginfull.asp') > -1) {
setTimeout(function(){$('#hidebox').hide()},2000);
} else {
$('#hidebox').show();
}
});
http://jsfiddle.net/userdude/Qt8uH/1/
You can try changing document.location.href to window.location.pathname;
So your code now says
var url = window.location.pathname;
if (url.indexOf('http://donorperfect.local/asp/loginfull.asp') >= 0) {
$('#hidebox').hide();
} else {
$('#hidebox').show();
}
This will help you!!! Try this. it grabs the URL from the address bar.
var url = window.location.href;
if(url == "http://www.promilitarybusinessnetwork.com/continueSearch.asp?categoryID=108") {
$('#website').html('<p>This is the Apartments Category page</p>');
} else {
$('#website').hide();
}});
if not .hide();. try .empty();