Alexandru Alexandru - 3 months ago 7
Javascript Question

Sync the same varaible in 2 functions Jquery

I've got a small script that generates an random (qID) like '#nr4', '#nr10' etc. assigned to a div that will be displayed on screen everytime the button gets clicked. I also have an 'img' that once it's clicked it redirects to tweet. The problem is that q and c variable dont get update the same way like if they would be in $('button').click( function(){}). I tried to add them in the same functions but it got me a bug..

$(document).ready(function() {
$('button').click(function() {

var nr = Math.floor(Math.random() * 10 + 1);
nr = '' + nr;
var qID = '#' + 'nr' + nr;
var q = $(qID + " > h4").html(); ///updates every time it gets clicked
var c = $(qID + " > h5").html(); ///updates every time it gets clicked

$('#qHome, #nr1, #nr2, #nr3, #nr4, #nr5, #nr6, #nr7, #nr8, #nr9, #nr10').hide();
$('button, img').show();
$(qID).show();

$('img').click(function() {
window.open('https://twitter.com/intent/tweet?text=' + q + c); //no more updated once clicked
})
})
});

Answer

Just declare q and c in the outer scope. You should also attach click function only once so you can also do it there

$(document).ready(function() {
  var q, c;
  $('button').click(function() {

    var nr = Math.floor(Math.random() * 10 + 1);
    nr = '' + nr;
    var qID = '#' + 'nr' + nr;
    q = $(qID + " > h4").html(); ///updates every time it gets clicked
    c = $(qID + " > h5").html(); ///updates every time it gets clicked

    $('#qHome, #nr1, #nr2, #nr3, #nr4, #nr5, #nr6, #nr7, #nr8, #nr9,   #nr10').hide();
    $('button, img').show();
    $(qID).show();

  });

  $('img').click(function() {
    window.open('https://twitter.com/intent/tweet?text=' + q + c);
  });
});