Solution 1 :

This should not be a click function in the first place, since it is not a repeatable process. Just do it once after loading the page.

;window.onload = function(){
  //REM: Building the correct links once on page load
  for(var tListOfLinks=document.querySelectorAll('a.sharelink'), i=0, j=tListOfLinks.length; i<j; i++){
    var item = tListOfLinks[i];

    //REM: The rest of the logic can stay
    if(item.href == 'mailto:?') {
        var subject = 'subject=' + document.getElementById('header').innerText;
        var body = "&body=Check out at this url : " + window.location.href;
        item.setAttribute('href', item.href + subject + body);
    } else {
        //item.setAttribute('href', item.href + window.location.href);
        item.setAttribute('href', item.href + encodeURIComponent(window.location.href));
    }
  }
};

//REM: For demonstration purpose, can be removed entirely.
function buildURI(item){ 
  console.log(item.href);
  alert(item.href)
}
<!-- REM: Requierd in your script -->
<span id = 'header' style = 'display: none'>Header</span>

<a onclick="buildURI(this)" href="https://www.facebook.com/sharer/sharer.php?u=" class="sharelink" target="_blank" title="Facebook"><img src="facebook32.png" />facebook</a>           
<a onclick="buildURI(this)" href="https://wa.me/?text=" class="sharelink" target="_blank" title="WhatsApp"><img src="whatsapp24.png">whatsapp</a>            
<a onclick="buildURI(this)" href="mailto:?" class="sharelink" target="_blank" title="Mail"><img src="envelope.png">envelope</a>

Solution 2 :

You should change else condition to else if, like this:

<script type="text/javascript">
                  function buildURI(item) {
                      if (item.href === 'mailto:?') {
                          subject = 'subject= + document.getElementById('header').innerText';
                          body = "&body=Check out at this url : " + window.location.href;
                          item.setAttribute('href', item.href + subject + body);
                      } else if (item.href === 'https://www.facebook.com/sharer/sharer.php?u=' || item.href === 'https://wa.me/?text=') {
                          item.setAttribute('href', item.href + window.location.href);
                      }
                  }
                </script>

Solution 3 :

Try this

 function buildURI(item) {
    if (item.href.includes('mailto:?')) {
        item.href='mailto:?';
        subject = 'subject=' + document.getElementById('header').innerText;
        body = "&body=Check out at this url : " + window.location.href;
        item.setAttribute('href', item.href + subject + body);
        return;
     }
    else if(item.href.includes('facebook.com')) 
            item.href="https://www.facebook.com/sharer/sharer.php?u=";
    else if(item.href.includes('wa.me'))
            item.href="https://wa.me/?text=";
    item.setAttribute('href', item.href + window.location.href);
}

Problem :

I want to dynamically generate url based on link click using js.

below is my code

<a onclick="buildURI(this)" href="https://www.facebook.com/sharer/sharer.php?u=" class="sharelink"
                target="_blank" title="Facebook"><img src="facebook32.png" /></a>
            <a onclick="buildURI(this)" href="https://wa.me/?text=" class="sharelink" target="_blank"
                title="WhatsApp"><img src="whatsapp24.png"></a>
            <a onclick="buildURI(this)" href="mailto:?" class="sharelink" target="_blank"
                title="Mail"><img src="envelope.png"></a>

function buildURI(item) {
    if (item.href == 'mailto:?') {
        subject = 'subject=' + document.getElementById('header').innerText;
        body = "&body=Check out at this url : " + window.location.href;
        item.setAttribute('href', item.href + subject + body);
    } else {
        item.setAttribute('href', item.href + window.location.href);
    }
}

problem is when I click the link, it generates href properly for the first time. But, when I come back to page after sharing the link of my page via email or fb, and tries to share in another link of the 3 links above, its appending the href to earlier generated one. how to deal with this issue?


I found a solution. Thanks all

<a onclick="buildURI(this)" class="sharelink"
                target="_blank" title="Facebook"><img src="facebook32.png" /></a>
            <a onclick="buildURI(this)" class="sharelink" target="_blank"
                title="WhatsApp"><img src="whatsapp24.png"></a>
            <a onclick="buildURI(this)" class="sharelink" target="_blank"
                title="Mail"><img src="envelope.png"></a>


const fbShareUrl = 'https://www.facebook.com/sharer/sharer.php?u=';
const WhatsAppShareUrl ='https://wa.me/?text=';
function buildURI(item) {
    if (item.title == 'Mail') {
        href='mailto:?';
        subject = 'subject=' + document.getElementById('header').innerText;
        body = "&body=Check out at this url : " + window.location.href;
        item.setAttribute('href', href + subject + body);
    } else {
        if(item.title == 'Facebook'){
            href = fbShareUrl;
        }else if(item.title == 'WhatsApp'){
            href=WhatsAppShareUrl;
        }
        item.setAttribute('href', href + window.location.href);
    }
}

this way I can manage social media urls in js file as well. Hope this is the ideal solution for this. If anyone have better idea please suggest.


easiest solution is adding ‘onclick = null’ at the end of my original method, as suggested in question’s comments. Will explore more about that update here, if its risky to use or not.

function buildURI(item) {
        if (item.href == 'mailto:?') {
            subject = 'subject=' + document.getElementById('header').innerText;
            body = "&body=Check out at this url : " + window.location.href;
            item.setAttribute('href', item.href + subject + body);
        } else {
            item.setAttribute('href', item.href + window.location.href);
        }
        item.onclick = null;
    }

Comments

Comment posted by Lain

Because

Comment posted by Safnas

Thanks!. I know the issue here. but, I am not getting a best way to deal with this, since this operator stores that element and whenever I click on either of the links, it appends to previous one. Please suggest me the correct way to do it dynamically.

Comment posted by Safnas

Thanks all. I got a better way to do it. remove the href attribute from all ‘a’ tags, then in function compare the button title and append that url. I will add the working code in question itself

Comment posted by JavaScript

Adding

Comment posted by JavaScript

From experience.

Comment posted by Safnas

why can’t I do it with onclick?? why I need to assign href by executing the method onload itself? what is user don’t want to click a url at all? I think I found a solution, thanks though

Comment posted by Lain

None said that you can not.

Comment posted by Safnas

‘This should not be a click function in the first place, since it is not a repeatable process’ , then what was this??

Comment posted by Lain

It was and is a recommendation. Not a dogma. You might argue what happens if the user clicks on no link, I might argue what happens if the user clicks on multiple or the same one twice. Choose what floats your boat.

Comment posted by Safnas

Thanks. I can use the your argument for a different case. not here.

Comment posted by Safnas

works for mail. but for facebook and whatsapp link to work, I have to reset the href value in similar way right? i think better to compare for ‘a’ type in function and initialize href to corresponding type and set the href attribute. any thoughts?

Comment posted by Safnas

Thanks, with your answer, I got the above thought. Now, I can manage the proper url in js as well, rather editing in html. I will update the correct way in question comment itself

Comment posted by M A Salman

if my answer helped you , please upvote. If you think that my answer is correct please mark as correct.Thank you

Comment posted by Safnas

Can’t do both since yours was not the ideal solution I was looking for. for workaround, I don’t need stack over flow. sorry buddy. Thanks anyways.

By