Winnipeg Photographer


How to use a variable with css and jquery

*!! Update !!* – Remove this line of code before going live. If you leave this in the xhtml code Internet Explorer will freak and you won’t have the effect you are looking for!

image

* NOTE * – You can read more about this issue here: How console.log can cause issues in Internet Explorer

I was banging my head with this one. I think part of my issue was I was using variable names that are already used in jquery or they might have some other meaning in javascript that was interfering with things. I also made a mistake by missing a set of apostrophes.

This is what the goal was:

I want the background of the un-ordered list to change according to the name of the class of the particular list item I am hovering over.

image

I had everything working with if statements. While it worked, if I added any more list items (li) to the page I would have to also change the jQuery code. Not fun! Not only was it NOT dynamic by using if statements,  it also took up so many more lines of code. It definitely wasn’t a good way of optimizing the code.

Using the console.log() function definitely helped me troubleshoot and track down what I was doing wrong!

Here’s the un-optimized code using if statements. (I had to line wrap the code to fit)

jQuery

image

This is the code I used to get the background to change dynamically:

jQuery

image

  1. Line 1 – Let’s run some JQuery after the page has been loaded.
  2. Line 2 – When ever I hover over the un-ordered list run some code. Because the UL is a block level element it will fill it’s space and create a container with everything inside of it.
  3. Line 3 – When ever I hover over one of the links run some code.
  4. Lines 5-7  – We’re going to build a path for the background image. Notice on Line 6 I give bgPic the class value. I named the background pictures the same name as the class but I added BG at the end. NOTE!!! – If (#mainContent a) had more then one class applied to it you would have to use a loop to get all the classes.
  5. Line 8 – This line isn’t needed but I figure I’d include it. If you use FireBug (Firefox plugin) you can silently find out what the value of the variable is.
  6. Line 11-12 – This is normally one line in my code. Notice how I put in the full URL of the background picture using a variable?
  7. Line 13 – Because there is tiny gap between the links and the links aren’t all the same size I created a blank tv for a background. This helped with a tiny bit of flicker when going over the items.
  8. Line 17 – When you hover outside the un-ordered list the background will go back to it’s original state.

Hopefully this will help people out if they are needing to use variables with jQuery.

PS – Here’s the HTML section that went along with the jQuery

xhtml

image


Leave a Reply