On scroll jquery change html header tag background image

below is my simple code to change the background image of header tag but it is not working at the moment

$(window).scroll(function() {
    if ($(this).scrollTop() > 400) {
        $("header").css("background", "url(http://www.kreativestudio.ca/wp-content/themes/parasponsive/images/header_bg2.png) repeat-x scroll 0px rgba(0, 0, 0, 0) !important");
    } 
    else {
        console.log('there');
        $("header").css("background", "url(http://www.kreativestudio.ca/wp-content/themes/parasponsive/images/header_bg.png) repeat-x scroll 0px rgba(0, 0, 0, 0) !important");
    }
});

whats the matter in this code?

Related posts

Leave a Reply

3 comments

  1. Remove !important from your jquery statement.

    $(window).scroll(function() {
        if ($(this).scrollTop() > 400) {
            $("header").css("background", "url(http://www.kreativestudio.ca/wp-content/themes/parasponsive/images/header_bg2.png) repeat-x scroll 0px rgba(0, 0, 0, 0)");
        } 
        else {
            $("header").css("background", "url(http://www.kreativestudio.ca/wp-content/themes/parasponsive/images/header_bg.png) repeat-x scroll 0px rgba(0, 0, 0, 0)");
        }
    });
    

    It’s not necessary because its an inline style and jquery css can’t handle it correctly.

    If however you need it to be important, check out this question:
    How to apply !important using .css()?

  2. the problem is in the applied CSS, in background-image you’re only allowed to define the background image, “background” is the deal for you, try this (I also changed the code slightly but that’s just a matter of taste ;)):

    $(window).scroll(function() {
    
        if ($(this).scrollTop() > 400) {
    
          $("body").css({
            "background": "url(http://www.kreativestudio.ca/wp-content/themes/parasponsive/images/header_bg2.png) repeat-x scroll 0px rgba(0, 0, 0, 0)"
          });
        } else {
            console.log("there");
    
          $("body").css({
            "background": "url(http://www.kreativestudio.ca/wp-content/themes/parasponsive/images/header_bg.png) repeat-x scroll 0px rgba(0, 0, 0, 0)"
          });
        }
    });
    
  3. Syntax is wrong change background-image to background and add few css
    html,body{
        width:100%;
        height:100%;
        float:left;
    }
    header {
        width:100%;
        height:100%;
        float:left;    
    }
    
    $(window).scroll(function() {
        if ($(this).scrollTop() > 400) {
            $("header").css("background", "url(http://www.kreativestudio.ca/wp-content/themes/parasponsive/images/header_bg2.png) repeat-x scroll 0px rgba(0, 0, 0, 0)");
        } 
        else {
            $("header").css("background", "url(http://www.kreativestudio.ca/wp-content/themes/parasponsive/images/header_bg2.png) repeat-x scroll 0px rgba(0, 0, 0, 0)");
        }
    });
    

    FIDDLE