Home > OS >  Transfer to a separate js file
Transfer to a separate js file

Time:10-11

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:[email protected]" onmouseover="this.href=this.href.replace(/x/g,'');">[email protected]</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?

CodePudding user response:

you can add a class to your email links

<a href="mailto:[email protected]" class="protected">[email protected]</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:[email protected]" class="protected">[email protected]</a>
<a href="mailto:[email protected]" class="protected">[email protected]</a>
<a href="mailto:[email protected]" class="protected">[email protected]</a>
<a href="mailto:[email protected]" class="protected">[email protected]</a>
<a href="mailto:[email protected]" class="protected">[email protected]</a>

CodePudding user response:

You can use for example unicode and unescape function:

var hidden = unescape("\u0048\u0069\u0064\u0064\u0065\u006e \u006d\u0065\u0073\u0073\u0061\u0067\u0065\u0021");
  • Related