Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

change <div> css property with javascript

Featured Replies

So I tried to make a bunch of buttons to change the background of another div

 

the javacript code I used was

 

HTML

<div id="btn1" onMouseClick="change()" ></div>
<div id="btn2" onMouseClick="change()" ></div>
<div id="btn3" onMouseClick="change()" ></div>

 

CSS

.div{
background-image:URL(.../images/image.jpg);
}

 

javascript

<script language="JavaScript">
function change(){
document.getElementById("btn1").style.backgroundImage = "URL:.../images/img2.jpg";
document.getElementById("btn2").style.backgroundImage = "URL:.../images/img3.jpg";
document.getElementById("btn3").style.backgroundImage = "URL:.../images/img3.jpg";
}
</script>

 

not working...at all, might be due to lack of caffeine and sleep.

 

if anyone has a solution I'd be greatful

 

note: I tried substituting the

document.getElementById("btn1")

 

for

document.getElementById("div")

 

not working

Edited by D.Schuster

Inline event handlers really aren't kosher, and it would be much cleaner and easier to achieve with jQuery using click() and css().

 

Not for a 3 line script. Why include 50kb of plain text and get the JS engine to read it all, and only do one thing with it? Hardly cleaner and easier.

 

The code should work like this:

 

document.getElementById("btn1").style.backgroundImage = ".../images/img2.jpg";

 

Without the URL bit, also at the top, <script type="text/javascript"> will probably help you out too.

Edited by Georgew

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.