Alter the style of a div by clicking on a button

Can the background image of a div be changed by selecting a button outside of the div?

For example:

HTML

<div id="change"></div>

<div id="buttons">
   <button class="button1">this</button>
   <button class="button2">that</button>
   <button class="button3">there</button>
   <button class="button4">then</button>
</div>

CSS

#change{
  background-image: url("this.jpg")
}

The desired effect is to change the background image to "that.jpg" when button 2 is clicked (same logic applies for each button; clicking button 3 will change it to "there.jpg", and button 4 to "then.jpg").

#change{
  background-image: url("that.jpg")
}

Answer №1

With the use of javascript, you have the ability to set the backgroundImage. Alternatively, if using jQuery, you would utilize $.css('background-image');

Another approach is to apply a class to the element using JS/jQuery and then specify the background-image in CSS for that class.

document.getElementById('button').addEventListener('click',function() {
  document.getElementById('change').style.backgroundImage = 'url(https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg)';
})
#change {
  background: #eee;
  width: 600px;
  height: 375px;
}
<button id="button">button</button>
<div id="change"></div>

document.getElementById('button').addEventListener('click',function() {
  document.getElementById('change').classList.add('bg');
})
#change {
  background: #eee;
  width: 600px;
  height: 375px;
}
#change.bg {
  background-image: url(https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg)
}
<button id="button">button</button>
<div id="change"></div>

Answer №2

To achieve this effect, JavaScript is required:

Your HTML:

<div id="buttons">
  <button class="button1" onclick="changeBG('image1.jpg')">choose</button>
  <button class="button2" onclick="changeBG('image2.jpg')">select</button>
  <button class="button3" onclick="changeBG('image3.jpg')">pick</button>
  <button class="button4" onclick="changeBG('image4.jpg')">opt</button>
</div>

<script>
  function changeBG(image) {
    var urlString = "url(" + image + ")";
    document.getElementById('change').style.backgroundImage = urlString;
  }
</script>

Although this method may not be the most elegant, it will help you get started.

Answer №3

Here is a handy jQuery tip for you!

$('#buttons button').on('click',function() {
    var newValue = $(this).text();
    $('#change').css('background-image','url('+newValue+'.jpg)');
});

Make sure to include this script within $(document).ready(function() {

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

What could be causing the images to not display on my HTML page?

My program is designed to display an image based on the result of the random function. Here is my HTML: <div> <h2>Player 0:</h2> <div id="MainPlayer0"></div> </div> Next, in my TypeScript fi ...

Unable to apply CSS styles to a form input using Ajax

Alright, so I've got this Ajax form that successfully fetches the data and displays it in #register_msg. However, I'm also trying to apply some styles to the input forms. Here's my Ajax code, along with the form. But for some reason, the st ...

Locating all elements on a webpage that are either above or below a specific element, capturing those that intersect visually

Is it possible to locate all the additional HTML elements that a particular element overlaps with, is positioned under, or intersects with? My goal is to ensure that this element is displayed above every other element. I am looking to identify all interse ...

Exploring the capabilities of JavaScript on the iOS platform

Here is the code I've written for my iOS application: webView = [[UIWebView alloc] init]; webView.delegate = self; [webView loadHTMLString:@"<script type=\"text/javascript\" src=\"myFile.js\"></script& ...

Troublesome update: Migrating XState's Reddit example from Vue 2 to Vue 3

Recently, I delved into the XState documentation and decided to explore the Reddit sample provided in the official guide. You can find it here: As I attempted to upgrade the sample implementation to Vue 3 following the work of Chris Hannaby, I encountered ...

Adjust input width based on content in VueJS

Is it possible to achieve the following using (Pug & CoffeeScript): input(placeholder="0", v-model.number="order[index]" v-on:change="adjustInput") ... adjustInput: -> event.target.style.width = event.target.value.length + 'ch' Even ...

Nuxt Js - Ensuring script is only loaded once during the initial page load

I already have a static website design, but now I'm converting it to Nuxt.js to make it more interactive. After running my Nuxt server with "npm run build...npm run start," the scripts load and my carousel/slides work fine. However, when I navigate to ...

Creating a three-column layout with position fixed in the center

I'm struggling with achieving a maximum width of 400px for the entire set of three columns and centering them. ---------------------------------------------------- | | | |----------------------------- ...

The issue of fonts module resolution in React-Native remains unsolved

I am embarking on a basic build project using 'create-react-native-app' and yarn as the package manager. My main goal is to incorporate 'native-base' for enhancing the user interface. So far, the only addition to my app.js file is a B ...

Present two logos on either side of a navigation bar with Bootstrap in between

I am facing an issue with the display of my two logos. One logo is supposed to be in the right corner and the other in the left, but the right logo is not appearing correctly. <header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" role="ban ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

Switching up the default font style within TinyMCE

After successfully changing the default font within the editor using the guidelines provided here, I have encountered a new issue. The original default font no longer appears in the font drop-down list. The previous default font was Verdana, and the new d ...

Hidden input field when inactive

Whenever I start typing in my input form, the text disappears after a moment. The only way to prevent this is by continuously pressing on a letter key on my keyboard. This issue began after I added a resizeInput attribute that adjusts the size of the inpu ...

Tips for updating the appearance of a ListItem with a click action

For my current project, I am using Material UI and React. One of my components is structured as follows: import React, { Component } from 'react'; import { List, ListItem } from 'material-ui'; import PropTypes from 'prop-types&apo ...

Is there a way to update the content within a div element that does not have a unique identifier

Is it possible to change the text "Here lies the text to be altered" using jquery? <div class="MyDiv"> <div> Here lies the text to be altered </div> </div> ...

What is the best way to configure my card components for a flex display?

Currently, I am in the process of learning React. I have a file named new_card_component.js that is responsible for displaying data fetched from the data.js file. The issue arises in my AirBnB.js file, where I'm passing the AirbnbApp module to a secti ...

Ways to make the background color white in Bootstrap 5

Can someone assist me in changing the background color of my portfolio to white? I attempted to use global CSS, but the black background on both sides of the page is preventing the change. return ( <> <Navbar /> <main className= ...

Trouble with reading from a newly generated file in a node.js program

Whenever I launch my results.html page, I generate a new JSON file and use express.static to allow access to the public folder files in the browser. Although my application is functioning properly, I find myself having to click the button multiple times f ...

Ion-content - Consisting of three elements with varying vertical positioning

I've been facing a challenge trying to include 3 different components (such as buttons, images, etc.) with distinct vertical alignment within the same ion-view. One should be aligned at the top, one in the middle, and one at the bottom. Take a look a ...

The issue with the second child of the nested datatable in Jquery is not

Within my project, I have implemented a jQuery nested datatable which includes two child rows for each row. Below is the code snippet that demonstrates this: $(function(){$(document).on('click','#tab td.control', function(){ var ...