Adam Khoury Design
Adam Khoury Design

Reputation: 39

Simplifying javascript

I have multiple fadeouts happening at the same time on various Ids, Is there any way of setting this up in one line as example:

This:

$("#bottle").on('click', function() {
  $("#container_inner01").fadeIn(1100);
  $("#container_inner02").fadeOut(1100);
  $("#container_inner03").fadeOut(1100);
  $("#container_inner04").fadeOut(1100);
  $("#container02").fadeOut(1100);
})

turned it to this:

$("#bottle").on('click', function() {
  $("#container_inner01").fadeIn(1100);
  $("#container_inner02,#container_inner02,#container_inner03,#container_inner04,#container02").fadeOut(1100);
})

I am sure its possible and its some syntax error I am doing.

Upvotes: -1

Views: 82

Answers (3)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

Doing what you have in the second script:

$("#bottle").on('click', function() {
  $("#container_inner01").fadeIn(1100);
  $("#container_inner02,#container_inner02,#container_inner03,#container_inner04,#container02").fadeOut(1100);
});

Will work, although you can sum this up to this:

$("#bottle").on('click', function() {      
    $("#container_inner01").fadeIn(1100);
    $("#container_inner02,#container_inner03,#container_inner04,#container02").fadeOut(1100);
});

Note that you have #container_inner02,#container_inner02 in you script repeating. Another way to do this is to add a class to all of them and using that class affects each item:

$("#bottle").on('click', function() {      
    $("#container_inner01").fadeIn(1100);
    $(".myClassName").fadeOut(1100);
});

Upvotes: 0

tzafar
tzafar

Reputation: 664

Try this

(function($){
    $("#bottle").on('click', function() {
        $('#container_inner01').fadeIn(1100);
        $('#container_inner02,#container_inner03,#container_inner04,#container02').fadeOut(1100);
    });
})(jQuery);

Upvotes: 0

urbz
urbz

Reputation: 2667

Why not give your elements a class and execute the script that way?

$("#bottle").on('click', function () {
    $("#container_inner01").fadeIn(1100);
    $('.test').fadeOut(1100);
});

JsFiddle demo

Upvotes: 2

Related Questions