This code is supposed to get the id from a clicked anchor tag in the middle of a ul with the id ‘links’ and then use that id for other purposes across the page, however the alerts have shown me that I keep getting ‘undefined’ as if the element has no id. I double check my source code and they do indeed have ids, so I’m not sure what the problem is.
$(function() {
$('ul#links > li > a').click(function() {
var planet = $(this).id;
alert(planet);
$('#planet').removeClass();
$('#planet').addClass('planet');
var bg = 'black url(../img/' + planet + '.jpg) fixed no-repeat center';
alert(bg);
$('body').css('background', bg);
});
});
Also this Jquery function is being used as a Javascript way of handling this kind of situation. I already had implemented a PHP solution which involved being redirected to a quick script that sets a cookie and returns the user to the previous page, then using the cookie to load a new CSS. Is there a way I could use that method as a backup to the JS method in the case that JS is disabled?
The page – http://schnell.dreamhosters.com/folio/
You were pretty close:
Firstly,
this.idwill get you the ID. The jQuery alternative is$(this).attr("id").Second, you can chain
addClass()andremoveClass()to save looking up the element twice. This isn’t necessary for your problem but is good practice.Third, unless you want your link to traverse somewhere you need to either prevent the default action (by calling
evt.preventDefault()on the event object passed to the callback) or simply ending withreturn false;(which also doesevt.stopPropagation()).Lastly, what you’re doing is well-suited to working with Javascript disabled because you can go to a page that does the same thing. I wouldn’t bother with setting the cookie and redirecting. If the script name URI is
/view/planet.phpdo this:Inside the same script you can do (I’m assuming PHP here; I didn’t see any mention of what you use):
while rendering the page.