Question

Probably very simple, but I can't seem to figure out how to do this:

function mouseOver(i,x){document.x.src="img/"+x+"/pic"+i+".jpg";}

The x in document.x.src suppose to represent the x selector, but it doesn't. How do I use the x selector as a target for the function?

Extra info: x is defined in a different function, it will become the name of the folder, in my case 'refugeelive'. I also want to name the target img 'refugeelive', which is the target for this function. This way by defining x as 'refugeelive' it selects the img from the right folder and sends it to the right target img.

Was it helpful?

Solution 2

In JavaScript, object.property is always the same thing as object['property'], so:

document[x].src

but it's poor practice to access page elements directly off document (and it may fail in some browser modes). Prefer to use document.getElementById(x) (and ensure you are using id="refugeelive" and not ancient name="refugeelive").

OTHER TIPS

Does not solve the problem explicitly, but you can build on this (or improve it)

<head>
<style>
div.myDiv {
  width: 100px;
  min-width: 100px;
  height: 100px;
  min-height: 100px;
  background-color: yellow;
}
</style>
</head>
<body>
<div class="myDiv"></div>
<script>
document.querySelector('.myDiv').addEventListener('mouseover',
function(e) {
    if(e.target.id)
      console.log(e.target.tagName.toLowerCase() + '#' + e.target.id);
    if(e.target.className)
      console.log(e.target.tagName.toLowerCase() + '.' + e.target.className);
});
</script>
</body>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top