In HTML, I have some images and a javascript function.
<img onmouseover="repl()" class="EN" ... />
<img onmouseover="repl()" class="FR" ... />
...
When user is on an image. I want to change my header text according to the language selected.
I need a way to have a "reference" to the sender of my function in javascript. But I have no idea because I have not used javascript for years. Please Help me !
function repl() {
// Missing Solution
// var lang = sender.attr("class"); <= Please correct me
var headerText = "";
if (lang == 'FR') {
headerText = "Cliquez sur le drapeau"
} else {
headerText = "Click on flag"
}
The best solution would be to bind the event using addEventListener
. Give all your images the same class, select them, then add events. I also suggest using data-*
attributes to store the language.
<img class="repl" data-lang="EN" ... />
<img class="repl" data-lang="FR" ... />
Then in your JavaScript:
window.onload = function(){// Make sure DOM is ready
// Get the images
var imgs = document.getElementsByClassName('repl');
// Loop over them
for(var i = 0, len = imgs.length; i < len; i++){
// Add the event
imgs[i].addEventListener('mouseover', function(){
// Get the language. "this" is the element we hovered over
var lang = this.getAttribute('data-lang');
var headerText = "";
if (lang == 'FR') {
headerText = "Cliquez sur le drapeau"
} else {
headerText = "Click on flag"
}
});
}
};