Sweta Sweta - 1 year ago 51
Javascript Question

How to display image ONLY in mobile view using media queries?

Can somebody help me modify the below code to display image only in mobile view. Right now, it is always visible.

<style type="text/javascript">
{float: left; width: 22px;cursor: pointer;background: none;}

@media only screen and (max-device-width: 568px) and (min-device-width: 320px) and (orientation: portrait)
{.icon-xyz {float: left;width: 22px;background: none;cursor: pointer;padding: 0 13px !important;}}


Following is the script to add image :

$(document).ready(function() {
var loc = window.location;
if (loc.toString().toUpperCase().indexOf('/home/') > -1)
$("#icon-xyz").css("background", "url(/images/Icon1.png) no-repeat");
if($.cookie("lang") == "es")
$("#icon-xyz").css("background", "url(/images/Icon2.png) no-repeat");


Answer Source

Since you're using max-device-width and min-device-width you won't be able to test this media query on your desktop browser, as it will only execute on screen sizes that match those parameters.

That may be one reason it appears not to work.

For testing purposes try using max-width and min-width instead, as these relate to the size of the browser window not the screen size of the device.

In fact, Google, in their words, strongly discourages use of *-device-width media queries for reasons relating to legacy browser reporting and adaptability (more details).

In terms of your question:

How to display image ONLY in mobile view using media queries?

Here's one method using just CSS:

.icon-xyz {
  display: none;
@media only screen and (min-width: 320px) and (max-width: 568px) and 
   (orientation: portrait) { .icon-xyz { display: inline; } }
<img class="icon-xyz" src="http://i.imgur.com/60PVLis.png" width="100" height="100" alt="">