Nicholas Nicholas - 1 month ago 8
jQuery Question

Check screen width with jquery

I have some code like this :

<script>
$(function(){
$(".flip").flip({
trigger: 'hover'
});
});
</script>


I want to check if media screen smaller than 480px I want to change the
trigger
into 'click' not 'hover' again.

I have tried code like this, but it's not worked yet.

<script>
$(function(){
if($(window).width() < 480){
$(".flip").flip({
trigger: 'click'
});
}else{
$(".flip").flip({
trigger: 'hover'
});
}
});
</script>


How could I check that screen width ?

Answer

Check The Code In Your Browser. So You Get Correct Idea.

function showWidth( ele, w ) {
  $( "div" ).text( "The width for the " + ele + " is " + w + "px." );
}
$( "#getp" ).click(function() {
  showWidth( "paragraph", $( "p" ).width() );
});
$( "#getd" ).click(function() {
  showWidth( "document", $( document ).width() );
});
$("#getw").click(function() {
  showWidth( "window", $( window ).width() );
});
 body {
    background: yellow;
  }
  button {
    font-size: 12px;
    margin: 2px;
  }
  p {
    width: 150px;
    border: 1px red solid;
  }
  div {
    color: red;
    font-weight: bold;
  }
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<body>
 
<button id="getp">Get Paragraph Width</button>
<button id="getd">Get Document Width</button>
<button id="getw">Get Window Width</button>
<div>&nbsp;</div>
<p>
  Sample paragraph to test width
</p>
 
<script>
function showWidth( ele, w ) {
  $( "div" ).text( "The width for the " + ele + " is " + w + "px." );
}
$( "#getp" ).click(function() {
  showWidth( "paragraph", $( "p" ).width() );
});
$( "#getd" ).click(function() {
  showWidth( "document", $( document ).width() );
});
$("#getw").click(function() {
  showWidth( "window", $( window ).width() );
});
</script>
 
</body>

Comments