Im new to javascript and programming in general, I don’t know whats going on but for some reason the background image doesn’t change with the change of the selected dropdown option.
When I try to test ‘dropdownClassMenuRead’ with the console output it say ” for some reason.
Im total new to programming and web dev in general btw.
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<title>Talent Point Calculator</title>
</head>
<body>
<select id="dropdownClasses">
<option>warrior</option>
<option>mage</option>
<option>paladin</option>
<option>rogue</option>
</select>
<div id= "graphicElements">
<svg id="svgsection" height="540" width="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>
</div>
<script src="main.js" defer></script>
</body>
JS:
var dropdownClassMenu = document.getElementById('dropdownClasses')
var dropdownClassMenuRead;
const svg_embed = "http://www.w3.org/2000/svg";
dropdownClassMenu.addEventListener('change',
function()
{
ChangeBackgroundImage();
}
);
function checkingSelectedClassDropdownMenu()
{
dropdownClassMenuRead = dropdownClassMenu.options[dropdownClassMenu.selectedIndex].text;
}
// changes the background according to the class dropdown menu
function ChangeBackgroundImage()
{
checkingSelectedClassDropdownMenu();
var doc = document.getElementById('graphicElements');
doc.style.backgroundImage = 'url(images/ + '+dropdownClassMenuRead+' + .gif)';
console.log(doc.style.backgroundImage);
}
CSS:
#graphicElements{
height: 540px;
width: 600px;
background-image: url("images/warrior.gif");
background-repeat: no-repeat;
background-color: rgb(132,132,132);
position: absolute;
}
2
Answers
The
doc.style.backgroundImage
needs to be adjusted a little to work with the quotes that js expects, with double quotes before theurl
and a single quote inside the parentheses. An alternative is you could use a template literal. I left a commented version of the template literal in the codeNote: I updated your js to take advantage of ES6+ utilizing
let
and arrow functions. It’s not necessary – just recommendation to use newer js standardsAs pointed out by wouch the ‘+’ within the first quoted url string is causing this error.
Actually you can ditch the inner quotes completely like so
url(images/warrior.gif)
.If you save image URLs in the
value
attribute, you could get the current<select>
value directly viavalue
property.If you don’t wan an additional value attribute, you could still simplify your script by using template literals e.g.
url(https://picsum.photos/id/${currentImgText}/200/300)
and move the image swap function to the change event listener.This way you don’t need global variables for the current image URL.