I don't really know what to title this. I am using jQuery so that when a user clicks a div, it transfers them to a page based off the div's class:
window.location = $(this).attr('class');
Say I'm connecting from the webserver (localhost). The first click may bring me to
localhost/info
If I click on about, it will bring me to
localhost/info/about
I was wondering how to get it to transfer me to
localhost/about
instead of
localhost/info/about
Firstly, location is an object. While assigning to it does work, it's better to assign to location.href.
Also, class is a bad choice of attribute to use for this, since it's very limiting. Instead, you should consider a data attribute:
<div data-href="/about"></div>
Note the / in the attribute value. That's what you need to make requests relative to the domain. Now you get there:
location.href = this.getAttribute("data-href");
PS. Every time someone writes $(this).attr(...), a unicorn dies.
You need to use an absolute path instead of a relative one. To do that you can prepend a / to the class.
window.location = "/" + $(this).attr('class');
Related
In the header
I have a link
Header
document.write('<a href="example.com/index.html?week=' + WeekW + '">');
The body changes based on the content so the WeekW changes with it.
Body
var WeekW = 53;
Ofcourse it gives me now it does not exist...what can be done ?
You have a few choices:
Set your variable before the document.write. This seems unlikely, since from what you say, you don't know the value of WeekW when you're writing your line.
Write a placeholder, and once you calculate your WeekW, you can fill in the placeholder. The easiest way to do this is simply write an anchor with a unique id:
document.write('<a id="myUniqueIdRightHere" >');
Later on, when you have set WeekW, go back and change your anchor:
document.getElementById('myUniqueIdRightHere').href = "example.com/index.html?week=" + WeekW;
Another alternative is to insert the full anchor with complete href into the document in the appropriate position after WeekW is set. You'd need to know enough about the surrounding parts of the document, but should be able to find something and attach the anchor at that point using things like the get* functions and appendChild.
in index.html background is changing randomly when you open it
var imgArr=['background.jpg', 'backgrounds2.jpg', 'backgrounds3.jpg'];
i=Math.round(Math.random()*2);
$('.wrap').css({'background': 'url('+imgArr[i]+') no-repeat fixed'});
in other pages i don't need to change background but use one from index.html
how can i save one var value from index.html and use it in other pages without changing?
You can use cookies or localStorage or even better sessionStorage.
var imgArr=['background.jpg', 'backgrounds2.jpg', 'backgrounds3.jpg'];
i = Math.floor(Math.random() * imgArr.length);
//fewer harcoded values is better :-)
$('.wrap').css({'background': 'url('+imgArr[i]+') no-repeat fixed'});
sessionStorage.setItem("bg", imgArr[i]);
Of course you should check if storage is available before attempting to access it, but it will be available in modern browsers.
The easiest way would be to jsut set a default in the CSS - your JS would then override that on index.html, and if you omit the js from the other pages then it will revert to the default.
You could also use JS to set a cookie and then read from that but then youd still need to plan for if someone accesses page without having the cookie set, so id probably go with the CSS option were I you.
If you are using any server side language then try SESSION to store the value.
If you are using only client-side language then try using cookie or pass the value through parameter to the next page.
You can add some element to index.html and check in your javascript if it exists it will mean that you are on index.html page and you should change background. For example add
<div id="iamindex"></div>
And you javascript:
if($('#iamindex').length) {
var imgArr=['background.jpg', 'backgrounds2.jpg', 'backgrounds3.jpg'];
i=Math.round(Math.random()*2);
$('.wrap').css({'background': 'url('+imgArr[i]+') no-repeat fixed'});
}
I have this HTML:
Track Your Package »
Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:
$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});
However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...
The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.
I hope I've been clear and you can help me. Thanks.
You can use .each() to iterate over each matching element and change them individually:
$('a[onclick^="window.open(\'TrackPackage.asp"]').each(function(index, element) {
element = $(element);
element.attr('onclick', element.attr('onclick').replace(/open\('/, 'open(\'http://www.example.com/'));
});
However, I don't think using links with a href of # and an onclick opening a window is as semantic as it could be. If possible, try changing the markup to this:
Track Your Package »
Now if someone is curious where it will lead them, the browser can show something useful in the status bar when you hover over it.
If you need to adjust the behavior further, add a class and bind for the click event. When they click, prevent the default action and open the window yourself, as you did before.
Why are you doing the click even inline like that? I would just output the links like:
Link Text
And then:
$('a[target=_blank]').click(function(){
var prefix = 'http://domain.com';
window.open(prefix + $(this).attr('href'));
});
I'm looking over some previous developers code and I come across this line:
location.href = '#' + variable;
Which has the effect of updating location.hash. Remove the '#' and of course it redirects to the non-existent url. Playing around a bit it seems I can set the hash via location.href as long as the value starts with '#'. This line or similar is used a lot, but I can't seem to find any documentation the supports this behavior of it updating location.hash by setting location.href this way.
I would like to see something showing this isn't just a happy accident that this works so I don't have to re-code all the situations where this is used. Anything you can link me to would help.
Would it be better to just changes these to properly set the location.hash anyway?
Thnks
At a guess this is because setting location.href to value is supposed to have the same behaviour as clicking a link whose href=value would; it's not supposed to replace the contents of the address bar, because then you'd have to build absolute URLs everytime you wanted to use location.href.
Assigning values to location and location.href was apparently there back in Javascript 1.0, so it's entirely possible this wasn't properly specified anywhere – neither the Mozilla or Microsoft documentation go into detail. HTML5 specifies the behaviour, most likely retroactively.
This is a good place to start your journey on the location properties.
https://developer.mozilla.org/en/window.location
By the way, #something is a valid url and assigning a new url to window.location cause the browser to navigate to the new destination.
#something is called hash and direct the browser to an anchor on the current document, or to the top of the document if the anchor does not exists.
http://docstore.mik.ua/orelly/webprog/DHTML_javascript/0596004672_jvdhtmlckbk-chp-10-sect-2.html
So what happens is when you set location.href to something that is not seen as an absolute path. The browser will automatically put the current url prepended to whatever value you are trying to set it to.
So "#section1" = "www.mysitethatistoocoolforschool.com#section1"
and "section1" = "www.mysitethatistoocoolforschool.comsection1" (this does not exist)
This URLs with a '#' char are called anchor based URLs, they're not supposed to redirect the user from the page, instead they just update the position of the page by some offset, the same way as setting the location.hash you cited.
As stated by Sii this works because when you change the location.href value it's like you're clicking on a link for example then you have the following equivalence:
<a href="#toc" >Go to Table of Contents</a>
Is the same as:
location.href = "#toc";
Both of them would result in your location.hash variable to have the value toc.
I am working on a website:
http://tawfiq-aliyah.co.uk/epic/Site2/
I want the user to be able to set the BackgroundImage. I have implemented this with the pop-up menu in the bottom left hand corner already. But what I want is for the data about the users choice of background image to be stored so that when they come back to the site or move to another page on the site it loads the same background image.
I have looked into java cookies on the w3schools.com website
w3schools.com/js/js_cookies.asp
I have looked at the example but I am not sure how to get the cookie to store the backgroundImage of the instead of storing a username.
Any help would be much appreciated.
Thanks
In the click handlers for the thumbnails in the background image selector you do things like this:
onclick="main.style.backgroundImage='url(images/back3.jpg)'"
If you replace that with a function:
onclick="setBackgroundImage('images/back3.jpg')"
and then
function setBackgroundImage(url) {
main.style.backgroundImage = 'url(' + url + ')';
setCookie('BG', url, 100); // Or however many days you want.
}
And then, in an onload handler, do something like this:
var bg = getCookie('BG');
if(bg)
main.style.backgroundImage = 'url(' + bg + ')';
You might want to do more sanity checking on the cookie value though, you have a list of available backgrounds kicking around so you could just check that bg is defined and that it is in the list.
Also, you might want to use absolute URLs for your images rather than relative ones, that makes it easier to move things around.
I've never worked with cookies in javascript, but looking at the w3c exampple you provided, wouldn'nt it be fine to use that technique and just store the url instead of the username? And then set the img:src or background-url or what ever you are using to that url from the getCookie function? (or later, whenever the dom is ready).
An alternative could be to use local storage, but it might be overkill for what you are trying to do.