Quantcast
Channel: SitePoint » Scott O`Hara
Viewing all articles
Browse latest Browse all 2

A Content-switching Component Built 3 Ways: jQuery, JS, CSS

0
0

Not too long ago, a friend of mine had constructed a UI component to change a page’s content based on the the current selection of a <select> element. Her code worked, but being new to JavaScript, she had built the component in jQuery and had asked me to help optimize it.

While not replicating the code exactly, I’ve created the following example to showcase the type of UI component she was trying to create:

[code language="html"]

Option 1 Content

...

Option 2 Content

...

Option 3 Content

...

[/code]

After optimizing it a bit, here is the jQuery we ended up using to toggle the display state of the selected content block.

[code language="javascript"] $(function() { $('.jqueryOptions').hide(); $('#choose').change(function() { $('.jqueryOptions').slideUp(); $('.jqueryOptions').removeClass('current-opt'); $("." + $(this).val()).slideDown(); $("." + $(this).val()).addClass('current-opt'); }); }); [/code]

So what’s going on here?

The above jQuery function looks for all the content blocks that have a class of ‘jqueryOptions’ and hides them by default.

Then when a user changes the selected option of the select input (which has an ID of ‘choose’), the function closes any potentially open content blocks using jQuery’s .slideUp() method and then opens the selected option with slideDown(). It does this by taking the value of the selected option (referenced as this) and referencing the element with the class name that matches the value in “this”.

Continue reading %A Content-switching Component Built 3 Ways: jQuery, JS, CSS%


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images