Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery to kick in if screen width is less than 500px

I have this code that shows content if clicked. The thing is that this function should only be availible if the screen/device width is 500px maximum. How would I go about doing this?

$(function () {
    $('.row1').hide();
    $('#show').toggle(function () {
        $('.row1').slideDown("slow");
        $(this).attr("src", "bilder/cancel.png");
    }, function () {
        $('.row1').slideUp("slow");
        $(this).attr("src", "bilder/add.png");
    });
});

UPDATE: I didn't do a good job explaining what I wanted to accomplish : / I I want this image to show when the screen width is above 500px. And when the width is less than 500px I want a line that say click here to show image and the image appears

like image 770
user2141649 Avatar asked Dec 01 '25 08:12

user2141649


1 Answers

You need to first get the screen width and then you can use an if statement to then run the code you posted above, if the screen width is above the certain width.

For example.

if($(window).width() > 500){
   $('.row1').hide();
   $('#show').toggle(function(){
      $('.row1').slideDown("slow");
      $(this).attr("src","bilder/cancel.png" );
   },function(){
      $('.row1').slideUp("slow");
      $(this).attr("src", "bilder/add.png" );
   });
};

EDIT

Looking at your comments you want to show an image else hide it. I would probably agree this would be nicer and easier to do with css media queries but please see the below edit which shows a JS solution.

if($(window).width() > 500){
   //show the image
   $('.row1').slideDown("slow");
   //etc...   
}else{
   //hide the image
   $('.row1').slideUp("slow");
   //etc...
}
like image 144
dev Avatar answered Dec 02 '25 23:12

dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!