0

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/

asked Apr 19, 2017 at 8:27
5
  • 1
    Do you need to do it via JS? Why not do it via CSS? Way better performance-wise. Wobbling is caused by elements being initially hidden and each time the window is resized, if the width is bigger than 780px, they will get shown. Commented Apr 19, 2017 at 8:30
  • 1
    Here is some help, without the wobbling: jsfiddle.net/e4g4a4m2 Commented Apr 19, 2017 at 8:30
  • I'm doing through Js because I want the answer div if the user clicks on some other div. Commented Apr 19, 2017 at 8:32
  • thanks @Mazz .. That was exactly what I wanted Commented Apr 19, 2017 at 8:37
  • Nice, i added it as answer Commented Apr 19, 2017 at 8:41

1 Answer 1

1

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

Mark
2,0433 gold badges22 silver badges43 bronze badges
answered Apr 19, 2017 at 8:40
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.