Kazzin Kazzin - 4 years ago 187
Javascript Question

Comparing old and new value of the same variable in jquery

I coded a website using Ajax and I want to compare clicked links to avoid page reloading.
My way to do it is having a var called

and storing url into it.
Everytime I click on the
, the url is stored into the Link,
then I call the
function, then the

var Link;

$('#button').click(function() {
Link = http://myurl ;

I have trouble with the data comparison. I want to compare the OLD value of
with the new Value, so I wrote a very vague approach (nonworking) and I wanted to know if somebody could help me.

function CompareLink() {
if ( Link == .data(Link)) {
//execute code

Answer Source

how about this?

<a href='something here' class='button' >something</a>
<a href='something else here' class='button' >something else</a>‚Äč

var link = null, oldLink = null;
$('.button').click(function() {
    link = $(this).attr('href');
    if (oldLink == null) {
         oldLink = link;
    CompareLink(link, oldLink);
    return false;

and then

function CompareLink(link, oldLink) {
    if ( link == oldLink) {
        // do something now

    oldLink = link;

function GoToLink(link) {
    window.location.href = link;

checkout this fiddle I made: http://jsfiddle.net/V9DyW/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download