Search code examples
javascriptjquerycssmedia-queries

How to change media query CSS with jQuery


I have two background images and I want to change this with jQuery.

For the #banner it works, but I don't now how to write the code for the @media screen and (max-width: 1024px)

.banner {
  background: url(../images/640px.jpg) 0px 0px no-repeat;
}

@media screen and (max-width: 1024px) {
  .banner {
    background: url(../images/900px.jpg) 0px 0px no-repeat;
  }
}
var selectData = {

  "bmw": {

    "1": "316i",
    "100": "520i",
    "101": "740i",
    "image1": "images/640px.jpg",
    "image2": "images/900px.jpg",

  },

};

jQuery(document).ready(function($) {
  $(document).on('click', '.specialLink', function(event) {
    var radio2 = document.getElementById('radio2');
    if (radio2.checked == false) {
      radio2.checked = true;
      toggleRadio();
    }
    $(".regio").html($(this).text());
    event.preventDefault();
    var b = $(this),
      background_image = '';
    buttonId = b.attr('id'),
      selectSet = selectData[buttonId],
      selectField = $('#specialLink');
    selectField.empty();
    //To change the background image of website
    $("#banner").css('background-image', 'url("' + selectSet.image1 + '")');
    $("@media screen and (max-width: 1024px)").css('background-image', 'url("' + selectSet.image2 + '")');
    if (selectSet) {
      //Remove image index form selectSet
      $.each(selectSet, function(k, v) {
        if (typeof k === 'string' && k === 'image') {
          return true;
        }
        selectField.append($('<option>', {
          value: k,
          text: v
        }));
      });
    }
    return false;
  });
});

Solution

  • You can use jQuery (window).resize() function, it will triggers when the browser window is resized.

    Here's an example using jQuery, javascript and css to handle resize events. (css if your best bet if you're just stylizing things on resize (media queries)) http://jsfiddle.net/CoryDanielson/LAF4G/

    Use this code for the solution you needed.

    $(window).resize(function(){
        if ($(window).width() <= 1024){ 
            $('.banner').css('background-image', 'url(' + imageUrl + ')');
        }   
    });
    

    Hope this help you out.