Madness Madness - 5 months ago 17
jQuery Question

Don't load the same JQuery load file twice

I have a dynamic container that updates when you click links by loading in the file name from the "data-target" attribute. I don't want the same link to be clicked twice however (effectively loading the same page twice).

Is there a way to prevent this?

JQuery:

$(document).ready(function(){
// Set trigger and container variables
var trigger = $('#nav ul li a'),
container = $('#ajaxContainer');

// Fire on click
trigger.on('click', function(){
// Set $this for re-use. Set target from data attribute
var $this = $(this),
target = $this.data('target');

// Load target page into container
container.load(target);

console.log(target);

// Stop normal link behavior
return false;
});
});


HTML:

<DOCTYPE html>
<html>
<head>
<title>My Site</title>
<link rel="stylesheet" type="text/css" href="/css/main.css" />
</head>
<body>
<nav id="nav">
<ul>
<li><a href="#" data-target="/home.php">Home</a></li>
<li><a href="#" data-target="/modules/Movies/index.php">Movies</a></li>
</ul>
</nav>
<div id="ajaxContainer">
<img id="logo" src="/images/logo.png" />
<?php include('home.php'); ?>
</div>

<script src="/js/jquery-1.12.4.min.js"></script>
<script src="/js/app.js"></script>
</body>
</html>

Answer

You can remove data-target and re-set it when the load() is completed (on callback parameter):

// Fire on click
trigger.on('click', function(){
    // Set $this for re-use. Set target from data attribute
    var $this = $(this),
        target = $this.data('target');  
    $this.removeAttr('data-target'); // delete de target

    // Load target page into container only if it's target set
    if(target) {
         container.load(target);
    }
    console.log(target);

    // Stop normal link behavior
    return false;
});
Comments