mardi 30 avril 2019

how to fix an if function which returns only the else statement

I'm writing a function that should display a specific text in an area depending on the src of an image, this function runs when the mouse is over another image. Always the same text is displayed besides the src of the image.

I've tried if-else functions, onmouseover or addEventListener none of those work


<img id="avatar" src="avatar1.jpg" alt="avatar" class="avatar">
<img src="icon.jpg" class='icon' id='icon'>
<p id='description'> specifit text should appear in here <p>



/*this funcion changes the source of 'avatar' and it works fine*/

const faces = [ "avatar1.jpg", "avatar2.jpg" ];
const avatar = document.getElementById('avatar');

function changeFace() {
  const face = avatar.src.split('/').slice(-1)[0];
  const index = faces.indexOf( face );

  avatar.src = faces[ ( index + 1 ) % faces.length ];
  console.log( avatar.src );
}

var icon = document.getElementById('icon');
icon.addEventListener('click', changeFace);

/*clicking on the 'icon' changes the src of 'avatar' from 'avatar1.jpg' to 'avatar2.jpg' and viceversa.*/

/*this function display 'text' in p 'description', it works fine*/

function writeText(text) {
  document.getElementById("description").innerHTML=text
}

/*this is the funcion that doens't work*/

function changeText() {
if (avatar.src === "avatar1.jpg") {
writeText('text number 1');}
else { writeText('text number 2');}
}

icon.addEventListener('mouseover', changeText);


it returns 'text number 2' regardless the src of 'avatar'enter code here

Aucun commentaire:

Enregistrer un commentaire