Reputation: 41
I want to change the size of an image when a button is clicked. I have following code:
HTML:
<img id="pizzaImage" src="img/pizza.png" alt="pizza">
JS:
var pizzaImage = document.getElementById('pizzaImage');
Button.onclick = function () {
pizzaImage.classList.add('changeSize');
};
CSS: (how the .changeSize should look like:)
img {
width: 20%;
}
Upvotes: 1
Views: 1241
Reputation: 721
classList.add() adds a class to the element. So img.classList.add('changeSize');
adds the class changeSize
to the image that you have selected, making the HTML for it look something like:
<img src="URL" class="changeSize" />
To make the image grow bigger with that class, you can use the CSS selector img.changeSize
The final code could look something like this:
document.querySelector("#changeImgSizeBtn").addEventListener('click', function () {
var img = document.querySelector("#imgID");
img.classList.add('changeSize');
});
img {
max-width: 150px;
}
img.changeSize {
max-width: 300px;
}
<img src="https://i.imgur.com/FrVmtJl.jpg" alt="cat img" id="imgID" />
<br />
<button id="changeImgSizeBtn">Change image size</button>
Upvotes: 1
Reputation: 81
you could try this:
Button.onclick = function () {
var img= document.getElementById('yourImgId');
if(img && img.style) {
img.classList.add("newStyle");
}
};
the html for the image would be:
<img src="src" id="yourImgId"/>
Add this CSS as well:
.newStyle {
width: 100px;
height: 200px;
}
Upvotes: 1
Reputation: 422
Try adding a .changeSize class to your css:
.changeSize {
width: 50%;
}
OR
img.changeSize {
width: 50%;
}
Upvotes: 0