Reputation: 113
I've got a class homework assignment involving nodes and nodelists that I thought would be simple, but I'm having difficulty figuring out how to change this one part.
I have been given an HTML, js, and css file along with some images. The goal is to change the background image in the tag by using a DOM method but NOT getElementByID. I am thinking to use querySelector, but can't figure out how to go between these internal and external style sheets. Here's the code:
HTML (with internal CSS)
<html>
<style>
#bkgImage {
background-image: url(images/bg2.jpg);
}
</style>
<body>
<aside>
Some text goes here<br />
<button id="button">Change background image</button>
</aside>
</html>
CSS (external)
aside
{
background-image: url(../images/bg1.jpg)
}
JS
var clickHandler = function()
{
}
objButton.onclick = clickHandler;
I'm thinking something like
var changeBackground = document.querySelector('bkgImage');
But I'm not sure where to go from here.
The aside loads bg1.jpg (which is in an external stylesheet) but when I click the button, I need it to change to bg2.jpg which is in an internal stylesheet. This is what is throwing me off the most I think.
Need to add some Javascript into that clickHandler function, but not exactly sure what all I need.
I'd appreciate any guidance on this. Thanks!
Upvotes: 0
Views: 2047
Reputation: 1835
You can just toggle the class of the aside to use a different background. I wouldn't alter the id with javascript or use the id for the background toggle styling... thats messy. Here is a fiddle.
http://jsfiddle.net/7na9xndk/1/
html
<aside class="bg1"><button id="button">change image</button></aside>
css
.bg1{
background:red;
}
.bg2{
background:lime;
}
js
var button = document.querySelector("#button");
var aside = document.getElementsByTagName("aside")[0];
button.addEventListener("click", function(){
aside.classList.toggle("bg1");
aside.classList.toggle("bg2");
})
Notice that I am using an event listener rather than a straight event handler.
Upvotes: 1
Reputation: 526
Here's your homework for you :)
https://jsfiddle.net/x2241vrq/
var button = document.getElementById('button');
var aside = document.getElementsByTagName('aside');
button.addEventListener('click', function(e) {
e.preventDefault();
aside[0].id = 'bkgImage';
});
Some notes.
<aside>
tag. So I took care of that for you.Upvotes: 1