*!! 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!
* NOTE * – You can read more about this issue here: How console.log can cause issues in Internet Explorer
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.
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)
This is the code I used to get the background to change dynamically:
- Line 1 – Let’s run some JQuery after the page has been loaded.
- 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.
- Line 3 – When ever I hover over one of the links run some code.
- 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.
- 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.
- 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?
- 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.
- 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