0

I'm using html to create a website and using javascript to add a blink function to some specific texts. I created a function in javascript and entered the id which I created in my html file. I want to add more ids so that my function can work for multiple ids. Here's my javascript function

function blink()
{
    let music = document.getElementById("music");
    if (music.style.visibility == 'hidden')
    {
        music.style.visibility = 'visible';
    }
    else
    {
        music.style.visibility = 'hidden';
    }
}
//Blink timer
window.setInterval(blink, 500);
  • You seem new to JavaScript, I recommend looking into JavaScript arrays this is a good resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array – Ameer Sep 23 '20 at 18:21
  • You can use , that is deprecated today. Check out this link to see how you can achieve blinking in CSS instead of javascript: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blink – Rickard Elimää Sep 23 '20 at 18:24
  • 2
    Does this answer your question? [How to correctly iterate through getElementsByClassName](https://stackoverflow.com/questions/15843581/how-to-correctly-iterate-through-getelementsbyclassname) . Ids are unique and can only be one of the kind, if you wan to use same function on multiple elements then you need to use class and loop throe it. WHen you get all elements with same class you create array and here is good article on all methods to loop in it; https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript , what you asking has been answered here on SO thousands of times – ikiK Sep 23 '20 at 18:27
  • Thank you all for your help! – Jay Buntolia Sep 23 '20 at 19:28

1 Answers1

1

You could do something like this:

function blink(id) {
  return function() {
    const el = document.getElementById(id);
    if (el.style.visibility === 'hidden') {
      el.style.visibility = 'visible';
    } else {
      el.style.visibility = 'hidden';
    }
  }
}

//Blink timer
window.setInterval(blink("music"), 500);
window.setInterval(blink("music2"), 500);