user6945897
user6945897

Reputation:

background-image style not working in HTML header

I'm trying to change the "background-image:" of a css class when a button is pressed.

JQuery:

$(function() {
    $('button').on('click', function() {
        $('.masthead2').css('background-image', 'url("../img/whiteheader.png")');
    });
});

CSS:

.masthead2 {
    position: relative;
    width: 100%;
    height: auto;
    min-height: 35rem;
    padding: 15rem 0;
    background-image: url("../img/roseheader.png");
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: scroll;
    background-size: cover;
}

When I press the button, the "background-image:" in the CSS style is removed. Then the HTML changes from this:

<header class="masthead2">

To This:

<header class="masthead2" style='background-image: url("../img/whiteheader.png");'

However, on the page; no image is displayed at all. I've tried copying the url directly into the css and the new image is loaded. So I'm confident the url is correct.

If the background-image is changed directly in the css, this should solve the problem.

Upvotes: 0

Views: 77

Answers (2)

Salman
Salman

Reputation: 112

I have checked, complete code, it's working at my end, please check your image url, if image is present there. Here is the code:-

    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Animation</title>
    <link rel="stylesheet" href="style.css" />
    <style>
        .masthead2 {
    position: relative;
    width: 100%;
    height: auto;
    min-height: 35rem;
    padding: 15rem 0;
    background-image: url("https://lh3.googleusercontent.com/proxy/ogwfaF0iwa05OnTNQFyD0rZ384sAN74p5xwJE6qfJmrEFcmgxlXo4zg22lrlaLcaS_hp9pFCu8s8QZ-GgDy37DxWVOHpq2B4IV35vb4wgHBWfJiYqI_AVARVMaguPane4Raedg=w530-h212-p-rw");
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: scroll;
    background-size: cover;
}
    </style>
</head>

<body>

  <header class="masthead2"></header>

<button>Submit</button>

</body>
<script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>
<script>
    $(function() {
    $('button').on('click', function() {
        $('.masthead2').css('background-image', 'url("https://upload.wikimedia.org/wikipedia/en/thumb/6/63/IMG_%28business%29.svg/1200px-IMG_%28business%29.svg.png")');
    });
});
</script>
</html>

Upvotes: 1

Raul
Raul

Reputation: 1024

the path to the image might be wrong. If it's inside the css the path is relative to the css file but inside html doesn't represent same location. Try an absolute path for the image. e.g

$(function() {
    $('button').on('click', function() {
        $('.masthead2').css('background-image', 'url("http://www.mywebsite.com/img/whiteheader.png")');
    });
});

Upvotes: 0

Related Questions