0

This is my code:

$(document).ready(function () {
var na = $("#navDivA");
var nb = $("#navDivB");
var ca = $("#contentA");
var cb = $("#contentB");
var la = $("#home");
var lb = $("#about");
var firstSession = true;

na.on("click", function () {
    ca.load("home.html", function(){
         alert("Loaded");
       });
   });

nb.on("click", function () {
    cb.load("about.html");
   });
}); 

<div id="wrapper">
    <div id="navDivA"><a id="home">Home</a></div>
    <div id="navDivB"><a id="about">About</a></div>
    <div id="contentA"></div>
    <div id="contentB"></div>
 </div>

Why does it alert multiple times every time I start to click? How can I avoid this? I want to load the html file once.

3
  • Multipe times per click or just one time each click? Maybe you are looking for one() Anyway, your question is missing context to make it clear Commented Nov 10, 2015 at 18:18
  • Could you also provide the HTML that goes with this script? Commented Nov 10, 2015 at 18:23
  • At the first click it fires once, but at the second he goes 3 times and and the third click he goes multiple times Commented Nov 10, 2015 at 19:28

1 Answer 1

1

You can use function one instead of on. According to documentation

The handler is executed at most once per element per event type.

which seems to be what you need. Change the code to

na.one("click", function () {
    ca.load("home.html", function(){
         alert("Loaded");
    });
});

nb.one("click", function () {
    cb.load("about.html");
});
Sign up to request clarification or add additional context in comments.

6 Comments

Ty for answer, but it doest work. He still fires the method multiple times.
@AntonStyopin Could you create jsFiddle demonstrating the issue?
I tried this code in jsFiddle and it worked fine. But in my code it doesnt. I think it might be because of the .html file inside the load()-function.
jsfiddle.net/xmtsu3nb/16 ... Here the one() function works but in my case he alerts multiple times after a few clicks
@AntonStyopin Could it be that you have more that one element with id="contentA" on your page? Unfortunately if we can't see reproduced issue in jsFiddle or similar service there is not much we can help with
|

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.