I am currently working on how to change a background image, with Javascript, on rails. I essentially have two small images that are set as small background images so that I have writing on top of them. The code looks like this:
HTML:
<div class="container">
<div class="row">
<div id="myImage" onclick="changeImage()" class="col-md-6 row-1 pic_1">
<div class="c-imageBlock_content">
<h2>Test</h3>
</div>
</div>
</div>
The main ID and Class to focus on here is id="myImage" and the class is pic_1.
CSS:
.pic_1 {
background-image: image-url("rice_shrimp.jpeg");
background-size: 100% 100%;
border-radius: 15px;
margin-left: 100px;
width: 450px;
height: 400px;
}
JS is the following:
function changeImage() {
var image = document
.getElementById('myImage').style.backgroundImage="url(wine_glass.jpeg)"
}
I know that my JS may not be complete. However, my main question is about the routing path-is it correct with just wine_glass.jpeg? I have never changed an image in rails but have done it plenty of times in a normal HTML/CSS document. Any help on how to do this, in rails, would be appreciated. Thank you! Please let me know if you need more information posted.
BASED ON THE FIRST RESPONSE BELOW: I have modified my code this way:
CSS:
.background-1 {
background-image: image-url("rice_shrimp.jpeg");
background-size: 100% 100%;
border-radius: 15px;
margin-left: 100px;
width: 450px;
height: 400px;
}
.background-2 {
background-image: image-url("wine_glass.jpeg");
background-size: 100% 100%;
border-radius: 15px;
margin-left: 100px;
width: 450px;
height: 400px;
}
HTML:
<div class="container">
<div class="row">
<div id="MyImage" class="col-md-6 row-1 background-1">
<div class="c-imageBlock_content">
<h2>Test</h3>
</div>
</div>
<div id="MyImage" class="col-md-6 row-1 background-2">
<div class="c-imageBlock_content">
<h2>Test</h3>
</div>
</div>
JS:
(function() {
var myImageEl = document.getElementById('MyImage');
var background2Enabled = false;
function toggleBackground() {
background2Enabled = !background2Enabled;
myImageEl.className = background2Enabled ? 'background-2' : 'background-1';
}
myImageEl.addEventListener('click', toggleBackground);
})();
Although I am now getting an error of Uncaught TypeError: Cannot read property 'addEventListener' of null. Not sure what this is but currently researching it.