I'm very new to programming. Ive used w3schools and freecodecamp to learn.
I know the basics within objects, arrays, functions and loops.
I know that I can write something like this to change an image.
function a(b) {var t; if(b === 1){t = "image.jpg"} document.getElementById("aide").src= t; } <br>button onclick="a(1)" <br>
img id="aide src="some.image"
How would a professional programmer do this? Is that called dom as i need to write onclick in html?
and.. I can make object/arrays such as var x = [{ rock: "Metallica" }];. I want a type="text" bar on a webpage that displays Metallica when a user writes Rock in the text field and submits it. How, and without dom if possible?
If you want to change an image, you can change its source:
// setting the variables used later
var btnNewImage = document.getElementById('btn-new-image')
var imageContainer = document.getElementById('image')
var counter = 1
// creating the string that will
// be the src of the image
function getImgSrc(currentCounter) {
// the current counter makes it possible to
// load different images on click
return "https://picsum.photos/200/300?random=" + currentCounter
}
// setting the src attribute of the imageContainer
// modifying the counter
function setImage() {
imageContainer.src = getImgSrc(counter)
// counter is mutated, so if it's called again
// it will be the next number
counter++
}
// adding event listener to the button
// instead of onclick handler
btnNewImage.addEventListener('click', function() {
// calling the setImage function, that will set
// the src attribute of the image
setImage()
})
// calling the setImage function for the first time
// so an image shows up on page load
setImage()
<button id="btn-new-image">NEW RANDOM IMAGE</button><br />
<img id="image" src="" />
The snippet above uses some things not really advised:
var instead of let & constcounter, calling setImage() function, referencing imageContainer inside the setImage() function, etc.)These are to be avoided, but I think at this point it makes no difference.
The API I used for images: Lorem Picsum
The trick is that addEventListener does not do anything - until there's a click on the button it's been registered to. When the click happens, it executes the function that's added to it.