Ad

Add Anchor Tag On Triggered Event In Javascript

- 1 answer

I have been struggling to add the <a></a> on mouseup or click event in the html document.

My requirement is to add anchor tag on the clicked part the moment user clicks in the html page.

document.documentElement.addEventListener('click', function(e){
  var tgt = e.target;
  if (tgt && tgt.nodeName === 'SPAN') {
    alert(e.target.id);
    tgt.classList.add('strong');
    var randomString = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
    alert('#'+randomString);
    var attrHref = '#'+randomString;
    tgt.id.add(randomString);
    tgt.href.add(attrHref);
    var newNode = document.createElement('div');
    //g.setAttribute('id', randomString);
    //alert( e.currentTarget === this );
    var a = document.createElement('a');
    a.href = attrHref;
    alert(a.href);
    //a.setAttribute('href', '#'+randomString);
    //g.appendChild(a);
    alert("afterAppendChild");
    tgt.href = attrHref;
    tgt.insertAdjacentElement("afterbegin", a);
    document.activeElement.insertAdjacentElement("afterbegin", a);
    alert("after insertA");
    alert('done');      
  }
});

In the html I do not have specific ids in the DOM elements which I can fetch so I am trying to add the <a></a> tag where user clicks. I am able to make the text bold but not able to add <a></a>

Kindly guide me on how to achieve this.

Ad

Answer

I was able to find a solution on this. Below is the source code.

<script type="text/javascript">
$(document).click(function(e){
  var randStr = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
  var attrHref = '#'+randStr;

    var div = $('<div id='+randStr+' class="a-wrapper">')
      .css({
        "left": e.pageX + 'px',
        "top": e.pageY + 'px'
      })
      .append($('<a id='+randStr+' href='+attrHref+'>Link'+randStr+'  </a>'))
      .appendTo(document.body);
      var blob = new Blob([$("html").html()], {type: "text/html;charset=utf-8"});
      saveAs(blob, 'page.html');
    });    
</script>

<style>
body {
  position: relative;
}

.a-wrapper {
  position: absolute;
  transform: translate(-50%, -50%);
    opacity: 1;
}
</style>
Ad
source: stackoverflow.com
Ad