1

I have a page with a JavaScript countdown and Bootstrap's tooltip JavaScript. They work very well, until I reload the page with jQuery's load(); function.

After I trigger load(); function couple of seconds after page load, other JavaScript stops working.

Check my page: http://areafordemos.freeoda.com/reload.html

I don't understand why simple refresh is causing that, and how to solve this problem? I tried to place JavaScript code to other places but no help.

Here is my Javascript code:

//JavaScript code for load() after few seconds.
setTimeout(function(){

    $().ready(function() {
    $(".reloadthis").load("reload.html .reloadthis");
    });


}, 5000);

//JavaScript code for tooltip.
$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});

//JavaScript code for countdown
function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.now();
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    if (t.total <= 0) {
      document.getElementById("clockdiv").className = "hidden-div";
      document.getElementById("timeIsNow").className = "visible-div";
      clearInterval(timeinterval);
      return true;
    }

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = '2016-01-01T12:00:00+02:00';
console.log(deadline);

initializeClock('clockdiv', deadline);
JJJ
  • 32,902
  • 20
  • 89
  • 102
LetsSeo
  • 875
  • 7
  • 20
  • Possible duplicate of [Jquery Event wont fire after ajax call](http://stackoverflow.com/questions/13767919/jquery-event-wont-fire-after-ajax-call) – JJJ Dec 29 '15 at 13:22
  • Will element before `.load` be the default target? I mean `$("#container").load("temp.html #innerContainer")` here `innerContainer` would be the target, but in OP example both values are same. Note: Apologies for stupid question. have never used it but will surely look into it later – Rajesh Dec 29 '15 at 13:24
  • The usage is correct. It replaces the contents of `.reloadthis` with the contents of the loaded document's `.reloadthis`. – JJJ Dec 29 '15 at 13:27

1 Answers1

3

When you bind an event to an element in javascript, the handler will live on the element itself rather than keeping a reference to it's class so when you reload new contents in the page, the JS won't be bound to them anymore.

You can do (atleast) two things to fix your issue.

One of them would be to re-run your JS by redoing the function calls.

e.g. Whenever you do $.load you can add a callback that should run after it's done fetching the contents of the page.

For instance:

$('.reloadthis').load('reload.html .reloadthis', function(resp, status, xhr) {
    call_functions_again(); // psuedo, you'd want to re-call your functions here to make them work with ajax loaded content
});

You could also try looking into event delegation but this serves different purposes like automatically binding events to newly added elements in the DOM by listening on the parent instead and letting the event bubble to children.

SidOfc
  • 4,552
  • 3
  • 27
  • 50
  • I really appreciate your help. I would like re-run my javascript codes. But how to apply `call_functions_again();` to them? I tried to copy/paste other javascript code into that block but probably what i did is ridicilious. – LetsSeo Dec 29 '15 at 13:35
  • 1
    @LetsSeo You just need to call `initializeClock('clockdiv', deadline);` again. – JJJ Dec 29 '15 at 13:37
  • `call_functions_again()` is a made-up function name by me, it doesn't do anything except give errors unless you've defined it yourself. In your case start out with replacing `call_functions_again()` with whatever functions need to actually be called to manipulate whatever is in `.reloadthis` – SidOfc Dec 29 '15 at 13:37
  • Thanks @SidneyLiebrand and @Juhanna, unfortunately this is the step I can't go any further. I even tried to change my javascript to `$().ready(function() { $(".reloadthis").load("reload.html .reloadthis"); $('[data-toggle="tooltip"]').tooltip(); });` to rerun tooltip javascript but didn't work. If you would like to help me I really appreciate it, if not thanks for your helps so far. – LetsSeo Dec 29 '15 at 13:47
  • @LetsSeo this is because the `$.load` will take some dozens of milliseconds and the `$('[data-toggle="tooltip"]').tooltip()` line will run before the ajax request is finished. – SidOfc Dec 29 '15 at 13:48
  • Well, you need to understand what you want to do and when you want to do it, it's hard to help without knowing that exactly (otherwise i'd write a full example) – SidOfc Dec 29 '15 at 14:08
  • All I want is get `tooltip` and `countdown` javascript work after `load()` function. With your example code, I know I can/should recall them. But I don't know how to do it. – LetsSeo Dec 29 '15 at 14:16