tyl-er tyl-er - 3 months ago 7
HTML Question

Can I add a string to the end of an href?

I'm making a random quote generator for FreeCodeCamp I need help making the tweet button work. My quotes are stored as strings in a an array. Is there away to add them on to the end of my href like this: href='http://twitter.com/home/?status=string ?

http://codepen.io/tyl-er/pen/KrjWVA?editors=1000

<head>
<script src="https://use.fontawesome.com/41c0e08ce5.js"></script>
</head>

<div class="flip">
<div onclick="randomIndex" class="card">
<div class="face front">
<!--logo here-->
</div>
<div class="face back">

<textarea rows="10" cols="30" type=text id="mytext"></textarea>
</div>
</div>
</div>

<div class="div10">
<p>(Spoliers maybe ¯\_(ツ)_/¯) <del>Written</del> and coded by Tyler Pelzer</p>
<a class="btn btn-social-icon btn-twitter" target="blank" href='http://twitter.com/home/?status=Twitter is like the lunch meeting with potential clients before you do the pitch. via @blogtyrant'>
<span class="fa fa-twitter"></span>
</a>
</div>


$('.flip').click(function printquote(){

var strings = []; // <--superlong array of quotes
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.getElementById("mytext").value = randomString;
//that was easy^

});

$('.flip').click(function(){
$(this).find('.card').addClass('flipped').mouseleave(function()
{
$(this).removeClass('flipped');

});
return false;
});

Answer

You can set href attributes much the same way as you have set the textarea's value. Add an ID on the link tag and:

document.getElementById('twitterLink').href = 'https://twitter.com/home?status=' + encodeURIComponent(randomString);

Edit: as you would like to do this separately to your flip click handler, let's refactor the following code:

$('.flip').click(function printquote(){
    var strings = []; // <--superlong array of quotes
    var randomIndex = Math.floor(Math.random() * strings.length); 
    var randomString = strings[randomIndex];
    document.getElementById("mytext").value = randomString;
    //that was easy^
});

Into this:

function getQuotes() {
    return []; // <--superlong array of quotes
}

function getRandomEntry(entries) {
    return entries[Math.floor(Math.random() * entries.length)];
}

$('.flip').click(function printquote(){
    document.getElementById("mytext").value = getRandomEntry(getQuotes());
    //that was easy^
});

That way you can share functionality to get the random quote with this new code:

$(document).ready(function() {
    var randomQuote = getRandomEntry(getQuotes());
    document.getElementById('twitterLink').href = 'https://twitter.com/home?status=' + encodeURIComponent(randomQuote);
});