Skip to content
Advertisement

Transfer to a separate js file

I am a noob in javascript, I need to hide a piece of code that I use in html in a separate js file and use it in several pages of the site, how can I do this?

This is the code that protects mail from spambots:

<a href="mailto:testx@testsitex.com" onmouseover="this.href=this.href.replace(/x/g,'');">test@testsite.com</a>

How can I transfer this code onmouseover="this.href=this.href.replace(/x/g,'');" to a separate js file and then use it here?

Advertisement

Answer

you can add a class to your email links

<a href="mailto:testx@testsitex.com" class="protected">test@testsite.com</a>

create a js file mouseover.js and add this code to it:

    document.addEventListener("mouseover", (e)=>{
      if(e.target.className === 'protected') e.target.href=e.target.href.replace(/x/g,'');
    });

and add this file to every page that contains email links (can be more)

<script type="text/javascript" src="mouseover.js"></script>

document.addEventListener("mouseover", (e)=>{
  if(e.target.className === 'protected') {
  e.target.href=e.target.href.replace(/x/g,'');
  console.log(e.target.href);
  }
});
<a href="mailto:testx1@testsitex.com" class="protected">test1@testsite.com</a>
<a href="mailto:testx2@testsitex.com" class="protected">test2@testsite.com</a>
<a href="mailto:testx3@testsitex.com" class="protected">test3@testsite.com</a>
<a href="mailto:testx4@testsitex.com" class="protected">test4@testsite.com</a>
<a href="mailto:testx5@testsitex.com" class="protected">test5@testsite.com</a>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement