1

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;
  });
});
1

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can change the image using picture tag of html5

<picture>
    <source media="(min-width: 650px)" srcset="img1.jpg">
    <source media="(min-width: 465px)" srcset="img2.jpg">
    <img src="img3.jpg">
</picture>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.