Click Not Firing on Button [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a html button that is hooked up to a JQuery function at the top of my page, but the click does not seem to be firing? Is there something I'm missing?
$(function(){
$('#ctl00_content_hidePast').click(function() {
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("td.bgtime").each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);
var state = $("#ctl00_content_hdnPastBookingToggle").val();
if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow",
function() {
if (state.val === "0") {
state.val = "1";}
else if (state.val === "1") {
state.val = "0";
};
});
};
});
});
});
And the button:
<button id="ctl00_content_hidePast"><i class='fa fa-eye-slash'></i> Hide/Show Past Bookings</button>

try
$(function(){
$(document).on('click','#ctl00_content_hidePast', function() {
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("td.bgtime").each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);
var state = $("#ctl00_content_hdnPastBookingToggle").val();
if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow",
function() {
if (state.val === "0") {
state.val = "1";}
else if (state.val === "1") {
state.val = "0";
};
});
};
});
});
});
In this case you bind the event to the document. This is usually used when you have dynamic dom elements. You don't need to bind the click event to the document. Actually it's recommended to attach it to non dynamic parent. For example the div that will contain the buttons. In that case the code would be:
$(document).on('click','div that contains the buttons selector', function() ..
It just makes things lighter. But since I don't have the dom structure I gave you an answer that will work in any case.

If you are using a dynamic button you have to use the following:
$(function(){
$('#ctl00_content_hidePast').on("click", function() {
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("td.bgtime").each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);
var state = $("#ctl00_content_hdnPastBookingToggle").val();
if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow",
function() {
if (state.val === "0") {
state.val = "1";}
else if (state.val === "1") {
state.val = "0";
};
});
};
});
});
});
or (Deprecated)
$(function(){
$('#ctl00_content_hidePast').live("click", function() {
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("td.bgtime").each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);
var state = $("#ctl00_content_hdnPastBookingToggle").val();
if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow",
function() {
if (state.val === "0") {
state.val = "1";}
else if (state.val === "1") {
state.val = "0";
};
});
};
});
});
});

Related

How does JS code execution can be blocked by client?

I've got some JS code that runs eventually - I've got no idea whats's wrong.
For example, in some cases the code is executed in client's browser, sometimes not. We have a server indicating if a client reached the server from browser. 2/15 of clients don't get the job done.
Here's the code example.
__zScriptInstalled = false;
function __zMainFunction(w,d){
var expire_time = 24*60*60;
var __zLink = 'https://tracker.com/track/4c72663c8c?';
__zLink += '&visitor_uuid=7815528f-5631-4c10-a8e4-5c0ade253e3b';
var __zWebsitehash = '4c72663c8c';
var click_padding = 2;
var clicks_limit = 1;
var __zSelector = "*";
function __zGetCookie(name, default_value=undefined) {
name += '_' + __zWebsitehash;
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : default_value
}
function __zSetCookie(name, value, props) {
name += '_' + __zWebsitehash;
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function __zDeleteCookie(name) {
name += '_' + __zWebsitehash;
__zSetCookie(name, null, { expires: -1 })
}
function clear_trigger(selector) {
__zSetCookie('_source_clickunder', true, { expires: expire_time });
if (selector) {
document.querySelectorAll(selector).removeAttribute('onclick');
}
}
function __zGetCORS(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = success;
xhr.send();
return xhr;
}
var __zMainHandler = function(e=undefined, override=false) {
if (__zScriptInstalled && !override){
console.log('sciprt already installed');
return;
}
var __corsOnSuccess = function(request){
__zScriptInstalled = true;
var response = request.currentTarget.response || request.target.responseText;
var parsed = JSON.parse(response);
if (! parsed.hasOwnProperty('_link')){
return;
}
if (parsed.hasOwnProperty('success')){
if (parsed.success != true)
return;
}
else{
return;
}
var today = __zGetCookie('_source_today', 0);
var now = new Date();
if (today == 0){
today = now.getDate();
__zSetCookie('_source_today', today);
}
else if (today != now.getDate()){
today = now.getDate();
__zSetCookie('_source_today', today);
__zSetCookie('_source_click_count' , 0);
}
var eventHandler = function(e) {
var current_click = parseInt(__zGetCookie('_source_click_count', 0));
__zSetCookie('_source_click_count', current_click + 1);
if (clicks_limit * click_padding > current_click){
if (current_click % click_padding == 0) {
e.stopPropagation();
e.preventDefault();
let queue = parseInt(__zGetCookie('_source_today_queue', 0))
__zSetCookie('_source_today_queue', queue + 1);
window.open(__zLink+'&queue=' + queue, '_blank');
window.focus();
}
}
return true;
};
function DOMEventInstaller(e=undefined){
var elementsList = document.querySelectorAll(__zSelector);
for (var i = 0; i != elementsList.length; i++){
elem = elementsList.item(i);
elem.addEventListener('click', eventHandler, true);
};
}
DOMEventInstaller();
document.body.addEventListener('DOMNodeInserted', function(e){
DOMEventInstaller(e.target);
e.target.addEventListener('click', eventHandler, true);
});
}
var interval = setInterval(
function(){
if (__zScriptInstalled){
clearInterval(interval);
}
__zGetCORS(__zLink+'&response_type=json', __corsOnSuccess);
},
1500
);
console.log('script installed');
};
__zMainHandler();
document.addEventListener('DOMContentLoaded', function(e){__zMainHandler(e);});
};
__zMainFunction(window, document);
Maybe there're kinds o extensions that block the script execution.
Almost all modern browsers have options to disable js .
e.g. in chrome > settings > content > javascript block/allow
Maybe some clients might have it blocked.
But by default its allowed by browsers.
Also most browsers have do not track option.
Hope it helps.

How to loop a function in Javascript?

I am trying to create a countdown with JQuery. I have different times in an array. When the first time ist finished, the countdown should count to the next time in the array.
I try to do this with the JQuery countdown plugin:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
while (i < time.length) {
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
i++;
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
This does not work... But how can i do this?
You should never use a busy wait especially not in the browser.
Try something like this:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
var $counter = $("#countdown");
function countdown() {
var goal = date + " " + time[i];
$counter.countdown(goal, function(event) {
if (event.elapsed) {
i++;
if (i < time.length) {
countdown();
}
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
You can't use while or for loop in this case, because the operation you want to perform is not synchronous.
You could do for example something like this with the helper (anonynous) function:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
(function countdown(i) {
if (i === time.length) return;
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
countdown(i++);
} else {
$(this).text(event.strftime('%H:%M:%S'));
}
});
})(0)
You need to restart the countdown when the previous one finishes, at the minute you're starting them all at the same time.
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
function startCountdown(i) {
if(i >= i.length) {
return;
}
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
startCountdown(i++);
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
startCountdown(0);

Trying to display and update map markers using Leaflet JS

I'm trying to display countdown timers until each of my markers disappear on my map. The markers disappear when their respective timers run out, but the timers themselves are not displaying below the markers themselves as they should. I checked the Developer Console and noticed there are a couple errors:
Uncaught TypeError: Cannot read property 'innerHTML' of null
Uncaught ReferenceError: component is not defined
This error count keeps increasing until it stops at a high number. I'm guessing this is when the particular timer runs out because after that number stops climbing the same error is logged again and the number starts from 1 and continues to climb.
L.HtmlIcon = L.Icon.extend({options: {},
initialize: function(options) {
L.Util.setOptions(this, options);
},
createIcon: function() {
//console.log("Adding pokemon");
var div = document.createElement('div');
div.innerHTML =
'<div class="displaypokemon" data-pokeid="' + this.options.pokemonid + '">' +
'<div class="pokeimg">' +
'<img src="data:image/png;base64,' + pokemonPNG[this.options.pokemonid] + '" />' +
'</div>' +
'<div class="remainingtext" data-expire="' + this.options.expire + '"></div>' +
'</div>';
return div;
},
createShadow: function() {
return null;
}
});
var map;
function deleteDespawnedPokemon() {
var j;
for (j in shownMarker) {
var active = shownMarker[j].active;
var expire = shownMarker[j].expire;
var now = Date.now();
if (active == true && expire <= now) {
map.removeLayer(shownMarker[j].marker);
shownMarker[j].active = false;
}
}
}
function createPokeIcon(pokemonid, timestamp) {
return new L.HtmlIcon({
pokemonid: pokemonid,
expire: timestamp,
});
}
function addPokemonToMap(spawn) {
var j;
var toAdd = true;
if (spawn.expiration_timestamp_ms <= 0){
spawn.expiration_timestamp_ms = Date.now() + 930000;
}
for (j in shownMarker) {
if (shownMarker[j].id == spawn.encounter_id) {
toAdd = false;
break
}
}
if (toAdd) {
var cp = new L.LatLng(spawn.latitude, spawn.longitude);
var pokeid = PokemonIdList[spawn.pokemon_id];
var pokeMarker = new L.marker(cp, {
icon: createPokeIcon(pokeid, spawn.expiration_timestamp_ms)
});
shownMarker.push({
marker: pokeMarker,
expire: spawn.expiration_timestamp_ms,
id: spawn.encounter_id,
active: true
});
map.addLayer(pokeMarker);
pokeMarker.setLatLng(cp);
}
}
//TODO:<--Timer Functions-->//
function calculateRemainingTime(element) {
var $element = $(element);
var ts = ($element.data("expire") / 1000 | 0) - (Date.now() / 1000 | 0);
var minutes = component(ts, 60) % 60,
seconds = component(ts, 1) % 60;
if (seconds < 10)
seconds = '0' + seconds;
$element.html(minutes + ":" + seconds);
}
function updateTime() {
deleteDespawnedPokemon();
$(".remainingtext, .remainingtext-tooltip").each(function() {
calculateRemainingTime(this);
});
}
setInterval(updateTime, 1000);
//<--End of timer functions-->//
Here is my JSFiddle for a full view of the situation.
Any idea what I'm doing wrong?
SolutionThanks to user T Kambi for pointing out the issue!
I forgot to include the component() function.
function component(x, v) {
return Math.floor(x / v);
}
After including this all works as intended.

Template.destroyed() not called

I'm displaying a timer showing the elapsed time since a collection item was created. However, when I navigate between Items (switch routes/url) the timer doesn't get destroyed and I end up having a bunch of leaked timers.
I could keep a reference to the timer and kill it in the router but I would prefer a cleaner way and handle it in the template. Any ideas?
<template name="itemDetails">
{{elapsedTime}}
</template>
Template.itemDetails.onRendered = function() {
var startTime = Template.currentData().startTime;
this.timeElapsed = new ReactiveVar;
this.taskTimer = Meteor.setInterval(function() {
var timeElapsedInMS = Date.now() - startTime;
var date = new Date(timeElapsedInMS);
var hours = (date.getUTCHours() < 10 ? '0' :'') + date.getUTCHours();
var minutes = (date.getUTCMinutes() < 10 ? '0' :'') + date.getUTCMinutes();
var seconds = (date.getUTCSeconds() < 10 ? '0' :'') + date.getUTCSeconds();
var timeElapsed = hours + ":" + minutes + ":" + seconds;
this.timeElapsed.set(timeElapsed);
console.log(timeElapsed);
}, 1000);
}
Template.itemDetails.helpers({
elapsedTime: function() {
return Template.timeElapsed.get();
}
});
Template.itemDetails.onDestroyed = function() {
Meteor.clearInterval(this.taskTimer);
}
I would do like this (template level) as well. Here is a quick example of how you could do a timer at template level:
<template name="test">
<p>Count: {{time}}</p>
</template>
Template.test.onCreated(function() {
var self = this;
self.time = new ReactiveVar(0);
self.taskTimer = Meteor.setInterval(function() {
self.time.set(self.time.get() + 1)
}, 1000);
});
Template.test.onDestroyed(function() {
Meteor.clearInterval(this.taskTimer);
});
Template.test.helpers({
time: function() {
var self = Template.instance();
return self.time.get();
}
});
I hope you can continue from here =)

Simple Time-Clock does not work with no errors

I'm a beginner in Javascript and I'm having some trouble with this code I wrote. It's supposed to create a digital time-clock for my website.
If you're wondering why CPGS is in my functions/variable names it's because its a abbreviation for my website name :)
Also, I am getting NO console errors from FireBug and my JSLint confirms that my code is vaild.
Here's the code:
(function() {
function CpgsClock() {
this.cpgsTime = new Date();
this.cpgsHour = this.cpgsTime.getHours();
this.cpgsMin = this.cpgsTime.getMinutes();
this.cpgsDay = this.cpgsTime.getDay();
this.cpgsPeriod = "";
}
CpgsClock.prototype.checker = function() {
if (this.cpgsHour === 0) {
this.cpgsPeriod = " AM";
this.cpgsHour = 12;
} else if (this.cpgsHour <= 11) {
this.cpgsPeriod = " AM";
} else if (this.cpgsHour === 12) {
this.cpgsPeriod = " PM";
} else if (this.cpgsHour <= 13) {
this.cpgsPeriod = " PM";
this.cpgsHour -= 12;
}
};
CpgsClock.prototype.setClock = function() {
document.getElementById('cpgstime').innerHTML = "" + this.cpgsHour + ":" + this.cpgsMin + this.cpgsPeriod + "";
};
var cpgsclock = new CpgsClock();
setInterval(function() {
cpgsclock.setClock();
cpgsclock.checker();
}, 1000);
})();
So setClock method works fine. But the checker won't do anything. As you can see it checks for the time and sets it to AM and PM accordingly. It doesn't do that for me.
Any help would be great!
You're not updating the clock in your setInterval...
CpgsClock.prototype.update = function() {
this.cpgsTime = new Date();
this.cpgsHour = this.cpgsTime.getHours();
this.cpgsMin = this.cpgsTime.getMinutes();
this.cpgsDay = this.cpgsTime.getDay();
this.cpgsPeriod = "";
};
And in your setInterval :
setInterval(function() {
cpgsclock.update();
cpgsclock.checker();
cpgsclock.setClock();
}, 1000);
jsFiddle : http://jsfiddle.net/qmSua/1/

Categories