Having issues with the background-image style not displaying correctly in the header of an

Trying to update the "background-image:" of a CSS class upon button click.

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

After clicking the button, the "background-image:" from the CSS style is cleared and the HTML changes like this:

<header class="masthead2">

Changes to:

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

Despite the change in HTML, the new image does not display on the page. Even though the URL seems correct as loading it directly into the CSS works fine.

Directly updating the background-image in the CSS should resolve the issue.

Answer №1

I have verified the code thoroughly, and it is functioning correctly on my end. I recommend double-checking the image URL to ensure that the image is present there. Below is the provided code snippet:

    <!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>

Answer №2

It's possible that the image path is incorrect. The path may need to be different depending on whether it is within a CSS file or HTML file. Consider using an absolute path for the image location.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent Purchase Button & Implement Modal on Store Page if Minimum Requirement is not Achieved

On my woocommerce shop page, I am facing an issue where all items are added to the mini-cart without meeting the minimum order requirement. This results in users being able to proceed to checkout without adding enough items to meet the minimum order amount ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

Tips for expanding an input field to span across two td elements

I am attempting to design a simple form. The issue I am encountering involves creating an input field that spans two td's in the second row of my table. Despite using the colspan="2" attribute within the td tag, the input field does not expand over tw ...

In the `componentDidUpdate()` method, the function `this.props` is not

I've encountered a peculiar issue that I just can't seem to figure out. It's possible that I missed something simple, but I'm stuck trying to solve this bug. Here's what's happening: In the child component, a counter is being ...

Should I retain a duplicate of the js library in the lib or vendor directory even if it has already been installed using npm?

Query 1 : As I install my project dependency libraries using npm, they are saved in the npm_modules folder. I wonder if it's necessary to also duplicate the library files like angular.js, angular-route.js in a separate lib or vendor folder for permane ...

relocate the image with an identical filename stored in the variable

Having trouble moving an image to a new position when clicking on its small thumbnail. I've attempted using jquery's find() function but it doesn't seem to be working... $('#slide1_controls img').click(function (event){ var sr ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...

Effective ways to enable users to upload files in a React Native app

Being in the process of developing a react native app, I am faced with the challenge of allowing users to easily upload files from their mobile devices (pdf, doc, etc). Unfortunately, my search for a suitable native component has proven fruitless. Can anyo ...

Is it possible to submit a select menu without using a submit button within a loop?

I'm having an issue with my code that submits a form when an option in a select box is clicked. The problem arises when I try to put it inside a loop, as it stops working. Can anyone assist me with this? Below is the code snippet causing trouble: &l ...

I am unable to make any changes to the CSS in the WordPress code that is already integrated

I have created a static web page to serve as my primary homepage. The page is built using HTML and CSS, with some PHP code pulled from My WordPress integrated into it. One of the functionalities I've added is to display the three most recent posts on ...

You cannot access the property 'subscribe' on a void type in Angular 2

fetchNews(newsCategory : any){ this.storage.get("USER_INFO").then(result =>{ this.storage.get("sessionkey").then(tempSessionKey =>{ this.email = JSON.parse(result).email; this.newSessionKey = tempSessionKey; this.authKey =JSON.stringify("Basic ...

Tips for posting images upon clicking a div instead of a submit button

I previously had a code that allowed users to click on the submit button and have the text inside a contenteditable div passed to upload.php using JQuery, inserted into a database, and immediately displayed. Now, I want to modify this code to also handle i ...

Error: Definition Already Exists

I'm currently debugging a layout and encountering some peculiar errors. The page is being served as DTD XHTML 1.0 Strict. The error message looks like this: ID "OFFICENAME" already defined: div class="office" id="officename" ID "OFFICENAME" origin ...

The button that is disabled can still be triggered using the ".click()" function

When programmatically triggering a disabled button with an "onclick" function, the function is still fired. See example below: <div> <input type="button" onclick="save()" id="saveButton" value="save" disabled="disabled" /> <input ...

Storing the timestamp of when a page is accessed in the database

I am currently working on a PHP website where users can register and access exclusive Powerpoint presentations. The owner has requested that I track the amount of time users spend viewing each presentation, but I am unsure of how to display and record th ...

Is there a way to incorporate the ACE code editor into a Vue project without relying on its built-in Vue

Just starting out with Vue and I'm looking to incorporate the ace code editor (this package) into my project. However, I want to avoid using the vue2-component & vue3-component versions for learning purposes. How can I achieve this? What's t ...

Using JQuery's $.post function can be unreliable at times

Looking for help with a function that's giving me trouble: function Login() { var username = document.getElementById('username').value; var password = document.getElementById('password').value; $.post("Login.php", { ...

Utilizing dynamic routes and incorporating additional search parameters within the URL structure in NextJS has never

Is there a way to use router.push(url); to redirect a user with a URL structure like this: [:lang]/something/[...dynamicRouteParams]?searchParam=true. The problem I'm facing is that the user ends up being redirected to a page with a URL structure lik ...

CSS styling doesn't take effect until the page is reloaded due to the failure of cssText

After generating a new list item, it appears that the CSS styling is not being inherited until the page is reloaded. Even though I have added styling using cssText dynamically, it doesn't seem to be working as expected. I've attempted using cssT ...

Tips on Modifying JSON Objects with JavaScript

In the code I'm working with, there's a generated line that creates an animated sidebar using a div. The width of this sidebar is controlled by the 'v' parameter, currently set to 85. <div id="sidebar" class="inner-element uib_w_5 ...