The Naga Tanker
The Naga Tanker

Reputation: 441

Jquery hide() / show() on window width

Hi guys please advise if this is the correct way of running the code on certain window width.

$(window).resize(function(){
var width = $(window).width();
if(width <= 780){
  jQuery(".answers").hide();
  jQuery(".container h4").click(function(){
    jQuery(this).next(".answers").siblings(".answers:visible").slideToggle();
    jQuery(this).next(".answers").slideToggle();
  });
}

else{
    jQuery(".answers").show();
}
})

on width bigger than 700px if I click on the question.. the whole thing keeps wobbling. Please advise --- the Jsfiddle link https://jsfiddle.net/bw6k874b/28/

Upvotes: 0

Views: 55

Answers (1)

Mazz
Mazz

Reputation: 1879

You just have to check with jQuery(".answers").is(':hidden') if .answers is already hidden.

$(window).resize(function() {
var width = $(window).width();
if (width <= 780) {
    if (jQuery(".answers").is(':hidden')) return; // This is the fix
    jQuery(".answers").hide();
    jQuery(".container h4").click(function() {
        jQuery(this).next(".answers").siblings(".answers:visible").slideToggle();
        jQuery(this).next(".answers").slideToggle();
    });
} else {
    jQuery(".answers").show();
}
})

Here is yours without the wobbling: https://jsfiddle.net/e4g4a4m2

Upvotes: 1

Related Questions