I have a script that runs on every page of my codeigniter site.
jQuery(document).ready(function($) {
Cufon.replace('h1');
$('#term').hint();
setTimeout('changeImage()',9000);
});
I only want that last line setTimeout('changeImage()',9000); if I'm on the base url and there are no segments in the URI (only want this to run on my homepage).
Is this possible to do some type of if statement with jQuery and find out if there are no segments in the URI?
Thanks
Well you can do this with simple javascript using window.location, you have three things to worry about: pathname, search and hash, the code will be something like:
var win_location = window.location;
if ( win_location.pathname === "" || win_location.pathname === "/" && win_location.hash === "" && win_location.search === "")
{
// I'M HOME NOW DO SOMETHING
}
// hash will be for things like #anchor in the url
// search will be for things like ?param1=john¶m2=doe
// so if you need those for some kind of dynamic handling on the home page remove the
// matching condition
use window.location
if ( window.location == YOUR_BASE_URL ) {
setTimeout('changeImage()',9000);
}
Related
I have this code :
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val());
window.location = "http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val();
}
In the console I have
http://myWebsite.dev/dailyGift?id_event=41?week_id=44?year_id=2016.
When I access directly works without problems, but jQuery does not make this redirect and I don't understand where is the problem.
You need to change all the ? with & except the first one
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'&week_id='+$('#week_id').val()+'&year_id='+$('#year_id').val());
}
Please replace all "?" with "&", Correct URL would be :-
http://myWebsite.dev/dailyGift?id_event=41&week_id=44&year_id=2016
Also it would be good if you encrypt ids for security purpose.
You say that you want to redirect to a link but you're merely changing the location.href value which is equivalent to clicking a link.
Location.replace() will load the new resource in place of the current one. The current page will not be added to the session history so it will not be possible to return to it using the back button.
I've also cleaned up the use of " and ' in the url string to make it cleaner.
if ($('#category').val() == 4){
var url = "http://"+window.location.hostname+"/dailyGift?id_event="+$('#sub-category').val()+"&week_id="+$('#week_id').val()+"&year_id="+$('#year_id').val();
console.log(url);
window.location.replace(url);
}
I am building a jQuery based web app and I want to use URL parameters to navigate around it.
I would like to display content based on the URL parameter, with the 'load()' function getting the main body of the web page from an external URL and replacing an element with it.
How would I create an if statement that use the following conditions...
If there are no parameters in the url, then use $("#toBeReplaced").load("home.txt");
If the parameter page is equal to about, then use $("#toBeReplaced").load("about.txt");
If the parameter page is equal to contact, then use $("#toBeReplaced").load("contact.txt");
...to determine what page of the app to display.
You can simply load the url using page variable if it is undefined then load home otherwise load whatever is in page variable.
var page = location.search.substring(1).split('=')[1];
if (page == undefined)
$("#toBeReplaced").load("home.txt");
else
$("#toBeReplaced").load(page + ".txt");
You can use different libraries or jQuery plugins to get url parameters in js. For this example I will use js-url. Include the url.min.js file into your page. Then just use this to get the parameter page by url("?page") and create a simple if.
$(function() {
var page = url("?page");
if( page === "about" ) {
$("#toBeReplaced").load("about.txt");
}
else if( page === "contact" ) {
$("#toBeReplaced").load("contact.txt");
}
else {
$("#toBeReplaced").load("home.txt");
}
});
function updateView(category) {
console.log( window.location.hash );
if (location.hash !== ""){
//convert #3 to 3.
//load video based on id
//myArray[sanitizedHash];
} else {
updateCategoryLabel(category);
currentList = updateVideosList(category);
chooseRandomVideoFromList();
}
}
This function is loaded on page load
How can I parse inside this function so that the the location.hash's '#' will be taken out of the URL?
In short I am trying to achieve www.mysite.com/3 versus www.mysite.com/#3
Thanks in advance!
Edit: I should add that the 'else' is basically randomizing on page load versus going to the direct url. This if statement will run on page load to check if the hash exists otherwise it will randomize as usual.
Altering the URL from 'www.mysite.com/#3' to 'www.mysite.com/3' will cause the browser to navigate to a new URL since www.mysite.com/3 is not the same page as www.mysite.com/#whatever.
If you just want a string with the first character of the hash trimmed try:
window.location.hash.substr(1)
You can get the window.location.hash and then replace the # with an empty string
if (location.hash !== ""){
var sanitizedHash = window.location.hash.replace("#", "");
//load video based on id
//myArray[sanitizedHash];
}
If your goal is NOT to trigger page load, you can use HTML5 History API to change URL from www.mysite.com/#3 to www.mysite.com/3 like that:
var id = location.hash.substr(1);
history.replaceState({id:id}, id, id);
Note that replaceState is used, because otherwise user can press back button to the browser and get back to the #3. If you want to allow that, replace replaceState with pushState. Hope that helps.
I'm developing a site that is heavily reliant on javascript for browser history manipulation and only uses one actual page file. I want the script to run a function whenever the user hits the base url of the site, but I'm not sure what method is appropriate. Figured I could make a quick comparison of the current window location, but what if the user types in www instead of http://, or none of them. Something tells me this should be really easy.
if (window.location.href == 'http://mysite.com') {
console.log('you hit the base url, yay');
myFunction();
}
It sounds like you want to isolate the path part of the URL.
function isHomePage() {
return window.location.pathname === '/' || window.location.pathname === '';
}
That should cover your bases, even if the URL is something like
https://www2.example.com:443/#hash
window.location.href always includes the protocol, so there's no issue if the user omits that when typing in the URL.
If by base url, you mean there is no path component or hash fragment, you can check for this as follows:
if (window.location.pathname==='/' && window.location.hash==="") {
console.log('you hit the base url, yay');
myFunction();
}
JavaScript can access the current URL in parts. For this URL:
http://mysite.com/example/index.html
window.location.protocol = "http"
window.location.host = "mysite.com"
window.location.pathname = "example/index.html"
Make it sure to use the host property
if (window.location.host === 'mysite.com') {
console.log('you hit the base url, yay');
myFunction();
}
How can I add something in JavaScript that will check the web site URL of someone on a web site and then redirect to a certain page on the web site, if a match is found? For example...
The string we want to check for, will be mydirectory, so if someone went to example.com/mydirectory/anyfile.php or even example.com/mydirectory/index.php, JavaScript would then redirect their page / url to example.com/index.php because it has mydirectory in the url, otherwise if no match is found, don't redirect, I'm using the code below:
var search2 = 'mydirectory';
var redirect2 = 'http://example.com/index.php'
if (document.URL.substr(search2) !== -1)
document.location = redirect2
The problem with that, is that it always redirects for me even though there is no match found, does anyone know what's going wrong and is there a faster / better way of doing this?
Use String.indexOf() instead:
if (window.location.pathname.indexOf('searchTerm') !== -1) {
// a match was found, redirect to your new url
window.location.href = newUrl;
}
substr is not what you need in this situation, it extracts substrings out of a string. Instead use indexOf:
if(window.location.pathname.indexOf(search2) !== -1) {
window.location = redirect2;
}
If possible it's better to do this redirect on the server side. It will always work, be more search engine friendly and faster. If your users have JavaScript disabled, they won't get redirected.