So I'm new to web development (career change) and I'm hitting a roadblock that I can't seem to get past.
I'm trying to write a script that will change the img src in my HTML. When I use inline JavaScript it does what I want and replaces the image:
<img id="book1" src="placeholder" alt="Book1">
<h5 class="title">TITLE by Author Name</h5>
<p>Book description</p>
<div class="center">
<button type="button" class="amz-btn" id="btn1" onclick="showImage()">Buy from Amazon</button>
<script type="text/javascript">
function showImage() {
let image = document.getElementById("book1");
if (image.src.match("placeholder")) {
image.src = "https://storage.googleapis.com/du-prd/books/images/9781538728529.jpg";
} else {
console.log("This is frustrating");
}
}
</script>
But when I transfer it to my external .js file I get a syntax error saying showImage is not defined.
How can I resolve this?
Here is the code as written just in the external file
document.getElementById("btn1").addEventListener("click", showImage)
function showImage() {
let image = document.getElementById("book1");
if (image.src.match("placeholder")) {
image.src = "https://storage.googleapis.com/du-prd/books/images/9781538728529.jpg";
}
else {
console.log("This is frustrating");
}
}
Someone suggested that I use addEventListener rather than onclick in the HTML so I've done that but I'm confident it's in entirely the wrong place and doing the wrong thing
I've tried running the following in the browser console and it runs perfectly but I still can't get it to work from the external file
const img = "https://storage.googleapis.com/du-prd/books/images/9781538728529.jpg";
document.getElementById("btn1").addEventListener("click", showImage);
function showImage() {
document.getElementById("book1").src = img;
}
Issue resolved!
const img = "https://storage.googleapis.com/du-prd/books/images/9781538728529.jpg";
document.getElementById("btn1").addEventListener("click", showImage);
function showImage() {
document.getElementById("book1").src = img;
}
The reason the above wasn't working was because I did something wrong with the window.addEventListener('load', (event) => { // all code here; }); but after removing that the image appears on a button click