I’m making a very simple pop up where I can choose from 8 types of content, all using the same format. It works by clicking on hidden divs that show on hover on the top section, of course as you can see I came up with a very long and large code for something that can probably be done with much less bolts and wires.
Since it’s a lot of lines I pasted all this in jsFiddle
Is there a way to make this lighter?
SOLVED… Yeees!
Thanks to all… here is the final script: jsFiddle Final in case someone else has the same difficulty
I see three things you could do to end up with less code:
First, jQuery has the
hovermethod to replace mouseover/mouseout behavior:Can be replaced as
That’s just a little less code though 🙂
Second, you are now defining a function for each eventhandler but you are only using these functions once. If you only use them once, you could create anonymous functions like this:
becomes
Finally, you can use a function to encapsulate the common parts of the code and pass the changing parts as parameters.
You could implement it like this:
The “div” selector uses the Attribute Equals Selector. You could also assign a class to all “animate” divs and select them using the class selector:
$("div.animate")which would select all<div class="animate">.What happens here is:
$(this).attr("swingLeft")as the left property.attr("wingLeft")gets the value for the swingLeft property as defined in your HTML markup.I stopped looking at your code at this point, the key is: Look at the code to be executed and see if you notice a pattern, something that you can generalize. You could then perhaps simplify the code further.
Also worth noting: Some people don’t like adding properties like “animate”, “swingLeft” etc to the HTML. Update As per pimvdb’s comment, you can use the jQuery data to be a bit ‘cleaner’.
The code could look like this then: