harley_woop
harley_woop

Reputation: 1849

Javascript/jQuery: Is there a better way to acomplish this in Javascript?

I have this code:

$(document).ready(function() { //Document Ready

$(".examples .example1").click(function() {

    $(".examples .example1 div").fadeToggle("slow");
    $(".examples .example1").toggleClass('focused');

});


$(".examples .example2").click(function() {

    $(".examples .example2 div").fadeToggle("slow");
    $(".examples .example2").toggleClass('focused');

});


$(".examples .example3").click(function() {

    $(".examples .example3 div").fadeToggle("slow");
    $(".examples .example3").toggleClass('focused');


});

}); // End

This just basically duplicates the same thing on 3 (only 2 in the example below) different elements- Click, Toggle a div, and toggle a class.

Working code here (Ugly and not as It appears in the site- lacking other css/less and images)

This works perfectly, but the (very small) JS person within me says that there must be a cleaner way of doing the same thing? Seems too repetitive and ugly.

Could anyone help to make this better code? (and hence me a better coder if I learn)

Upvotes: 0

Views: 56

Answers (2)

ayyp
ayyp

Reputation: 6598

$(document).ready(function() { //Document Ready
   $('.examples > span[class^="example"]').click(function() {
      $(this).toggleClass('focused').children('div').fadeToggle('slow');
   });
}); // End 

This will target a span child if .examples with a class name that begins with example. It will the toggle the focused class on this element before moving on the find the child div and toggling slow on it.

Codepen link: http://codepen.io/anon/pen/DBHFy

Upvotes: 1

epascarello
epascarello

Reputation: 207501

Use a common class on all of the elements. You can than use this to reference the element that was clicked on.

$(".examples>span").click(function() {   
    $(this).toggleClass('focused').find("div").fadeToggle("slow");    
});

Upvotes: 3

Related Questions