conan
conan

Reputation: 1335

what is the alternate way to do a function based on window width jquery?

I am trying to show the button and hide the stuff when the width <450, if >450, do the switch way, hide the button and show the stuff. There is no problem to hide and show with the css code, but the problem is once I click the button in <450, the stuff show up, if I go back to >450 screen, the button will not hide again. I had tried to put window.resize in the jquery, it give me weird performance. Click run the code to see it. Appreciate.

if ($(window).width() < 450) {

var show_stuff=$('#all_vote_menu');
var button_menu=$('#button');

     	$(button_menu).on('click', function(){
			
			$(show_stuff).show(400,'swing');
			$(button_menu).hide();
		    
		});
		
		$(document).mouseup(function (e){
	    if (!show_stuff.is(e.target) // if the target of the click isn't the container...
	        && show_stuff.has(e.target).length === 0) // ... nor a descendant of the container
	    {	

			$(show_stuff).hide(400,'swing');
			$(button_menu).fadeIn();
		
	    }
	});
  }
#button{
     display:none ;/*hide when >450px*/
     
   }
   .all_vote_menu{
      width:200px;
      height:200px;
      background:yellow;
   }

@media screen and (max-width: 450px)  {

#button{
     display:block ;/*show when <450px*/
     color:green;
   }
   .all_vote_menu{
   	display:none;/*hide when <450px*/
   }
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" id="button" name="all_vote_show" value="Menu"/>
<div class="all_vote_menu" id='all_vote_menu'>hello</div>

Upvotes: 0

Views: 63

Answers (2)

epascarello
epascarello

Reputation: 207501

Get rid of the width check if ($(window).width() < 450) {

Add check in the if that is doing the showing

$(document).mouseup(function (e){
    if ($(window).width() >= 450 && !show_stuff.is(e.target) ...

Upvotes: 1

user2232273
user2232273

Reputation: 4964

you don´t need the if condition to verify the window width because the button is only accessible when the window is smaller then 450px.

remove this and it works.

Try this DEMO

jquery code:

var show_stuff=$('#all_vote_menu');
var button_menu=$('#button');

        $(button_menu).on('click', function(){

            $(show_stuff).show(400,'swing');
            $(button_menu).hide();

        });

        $(document).mouseup(function (e){
        if (!show_stuff.is(e.target) // if the target of the click isn't the container...
            && show_stuff.has(e.target).length === 0) // ... nor a descendant of the container
        {   

            $(show_stuff).hide(400,'swing');
            $(button_menu).fadeIn();

        }
    });

Upvotes: 2

Related Questions