0

To start, here's a small project I made that throws a new fact every time the user presses the New Fact button. Source code available here. Then I made a Twitter button to tweet that quote.

As you can see in main.js file, there's a variable called quotes which is an array of 40 quotes (snipped in the code below).

// var quotes defined above, an array of 40 quotes

$(".quoter").click(function() {

        // To generate a random number
        function randomRange(myMin, myMax) {
            return Math.floor(Math.random() * (myMax - myMin + 1) + myMin); 
        }

        i = randomRange(0, 40);
        //Using the random number generated above to fetch a quote  
        $(".lead").text(quotes[i]);  

        var uriLink = encodeURIComponent(quotes[i]);

        $(".tweeter").click(function(){ 
            window.open("https://twitter.com/intent/tweet?text="+uriLink+, "_blank");
        });
    });

Whenever the user clicks the Tweet button, it opens up multiple twitter tabs for each i. I want the tab to be opened for the current quote only. I tried keeping the two functions separate, and not nested but then quotes[i] becomes inaccessible resulting in undefined.

2
  • what is the specific problem and what is your question? Commented Dec 28, 2016 at 23:22
  • @charlietfl I want only one tweet tab to open which contains the current fact whenever the user presses the tweet button. Commented Dec 28, 2016 at 23:25

1 Answer 1

1

Since you're storing the text that you're URI-encoding in the .lead element, here's one way you can separate the functions:

$(".quoter").click(function() {
  function randomRange(myMin, myMax) {
    return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
  }

  i = randomRange(0, 40);

  $(".lead").text(quotes[i]);
});

$(".tweeter").click(function() {
  var uriLink = encodeURIComponent($(".lead").text());
  window.open("https://twitter.com/intent/tweet?text=" + uriLink + , "_blank");
});
Sign up to request clarification or add additional context in comments.

3 Comments

I tried that too, but that will give me just one quote, the initial one. It won't update as I iterate.
@Hyperbola Are you sure? The way it's written here, it will get the current text of the .lead element each time .tweeter is clicked.
Thanks, it's working now. I had tried the same thing but don't know why it didn't work out then. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.