The following code tracks the number of clicks on the element and then submits the result to Facebook Pixel. However, the event is not triggered for some reason.
Thought it's a variable scope problem, changed countClicks to global but it didn't change anything.
$(document).ready(function () {
if(window.location.href.indexOf("products") > -1) {
var countClicks = 0;
$(".product-single__thumbnail-image").click(function () {
countClicks++;
});
function firePixelSlideshowView() {
fbq('trackCustom', "ProductSlideshowImageView", {
imageView: countClicks,
});
}
window.onbeforeunload = function () {
firePixelSlideshowView();
return null;
}
}
});
I solved the problem by using jQuery unload() function instead of vanilla Javascript and it worked.
Related
This is my script -
my script alert when someone touch on any place on the page .
I am trying to execute alert only one time and not on every click.
This is the code i built which alert any time .
$( document ).ready(function() {
var click_count = 0;
if (click_count == 0){
$('body').click(function(){
alert();
var click_count = 1;
});
}
});
You have your if in the wrong place. You want it inside the click handler (the code that runs when the click occurs), not outside it. You also need to remove the var from var click_count = 1; so you 're using the one declared in the ready callback, not the one declared in the click handler:
$(document).ready(function() {
var click_count = 0;
$('body').on("click", function() {
if (click_count == 0) {
alert("Hi there");
click_count = 1;
}
});
});
Testing 1 2 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(Here's a runnable version for mobiles where Stack Snippets aren't rendered: http://output.jsbin.com/taropelopu)
But, rather than using click_count, I'd suggest removing the event handler after the first click. You could do that with off, but jQuery even has a function specifically for adding a handler you remove the first time it's called: one (rather than on):
$(document).ready(function() {
$('body').one("click", function() {
alert("Hi there");
});
});
Testing 1 2 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(Runnable version for devices where Stack Snippets don't render: http://output.jsbin.com/wivoroluzu)
With plain JavaScript you can do
let clicked = false;
const clickOnce = () => {
if (!clicked) {
alert('clicked');
clicked = true;
}
};
document.body.addEventListener('click', clickOnce);
some body content
And you don't even need a clicked variable to store the state. Just remove the event listener once it is triggered.
const clickOnce = () => {
alert('clicked');
document.body.removeEventListener('click', clickOnce)
};
document.body.addEventListener('click', clickOnce);
some body content
I have a problem with button click does not firing when it dynamically created,
I know, here is the solution.
Question is this:
I am using SignalR. I must declare click event (to call some hub method) when chat hub is started. Please see below
button click works in this situation
$(document).on('click', "#chatlist li .gobtn", function (e) {
var id = $(this).closest("li").data("message-id");
});
But i should call it from here
$.connection.hub.start().done(function () {
//button click not fires here but it must be here
$('#chatlist li .gobtn').click(function () {
var id = $(this).closest("li").data("message-id");
chat.server.sendAnswer(id);
})
})
Please help if you have any idea to solve it.
If you change your code like below, i think it works
var chat;
var _sendAnswer;
$(function () {
var chat = $.connection.chatHub;
$.connection.hub.start().done(function () {
_sendAnswer = function sendAnswer(id) {
chat.server.sendAnswer(id);
}
});
$(document).on('click', "#chatlist li .gobtn", function (e) {
var id = $(this).closest("li").data("message-id");
if (_sendAnswer != undefined && typeof _sendAnswer == 'function') {
_sendAnswer(id);
}
});
});
I wish you good luck
I'm still a little new to jQuery events.
I'm trying to write jQuery a wrapper/framework of the Asp.NET UpdatePanel that automatically tracks UpdatePanel async updates.
I want to be able to do something like
$("#myUpdatePanel").on("update", myFunc);
and have it run some handler with this as the updated UpdatePanel. I actually have this bit working.
I also want to be able run a function exactly once any time one or many UpdatePanels update.
$.updatePanel.on("update", myRunOnceFunc);
This is where I'm having issues.
I've defined my wrapper:
// wrap updatePanel reload functionality
$.updatePanel = (function () {
var prm;
var UpdatePanel = function () { };
UpdatePanel.prototype = { };
// initialize on $(document).ready()
$(function () {
prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm) {
prm.add_pageLoaded(function (s, e) {
$.each(e.get_panelsUpdated(), function () {
// call panel-specific update event handlers
$(this).trigger($.Event("update"));
});
// triggered once no matter how many panels were updated
$(UpdatePanel).trigger($.Event("update"));
});
}
});
return $(UpdatePanel);
})();
Then in my code that uses $.updatePanel:
$(function() { $.updatePanel.on("update", myRunOnceFunc); });
What I'm finding is that myRunOnceFunc is being run during both $(this).trigger($.Event("update")); and $(UpdatePanel).trigger($.Event("update"));.
Any ideas why and how to fix it?
I figured out what was wrong.
Rather than return $(UpdatePanel);, I needed to call return $(new UpdatePanel());. Then I needed to replace $(UpdatePanel).trigger(...) with $.updatePanel.trigger(...). Code below:
// wrap updatePanel reload functionality
$.updatePanel = (function () {
var prm;
var UpdatePanel = function () { }
UpdatePanel.prototype = { };
$(function () {
prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm) {
prm.add_pageLoaded(function (s, e) {
$.each(e.get_panelsUpdated(), function () {
$(this).trigger($.Event("update"));
});
// triggered once no matter how many panels were updated
$.updatePanel.trigger($.Event("update"));
});
}
});
return $(new UpdatePanel());
})();
I have a refresh function:
function refresh(nRefresh)
{
TimerSetting = document.all.curRefresh.Timer;
document.all.curRefresh.Timer = 'On';
nTimeOut = nRefresh;
updateKnlButtons();
psStatusUpdate();
}
This function reload the page.
After clicking on a button I give refresh(5) to refresh a page after 5 seconds. Due to some reason I want to fire a function after refresh function is completed, but this function is getting fired before refresh function is completed. How to make sure disable function is called after refresh function is completed?
function disableButton()
{
idStopSelBtn.style.cursor='wait';
idStartSelBtn.style.cursor='wait';
idBounceRunningBtn.style.cursor='wait';
idStopAllBtn.style.cursor='wait';
idStartAllBtn.style.cursor='wait';
idBounceSelBtn.style.cursor='wait'
idStopSelBtn.src='images/Button/Disabled/Stop-Selected.gif';
idStartSelBtn.src='images/Button/Disabled/Start-Selected.gif';
idBounceRunningBtn.src='images/Button/Disabled/Bounce-Running.gif';
idStopAllBtn.src='images/Button/Disabled/Stop-All.gif';
idBounceSelBtn.src='images/Button/Disabled/Bounce-Selected.gif'
idStartAllBtn.src='images/Button/Disabled/Start-All.gif';
idStopSelBtn.onclick="return false";
}
You may just add another parameter (disable flag) to achieve the desired result.
function refresh(nRefresh, disable) {
TimerSetting = document.all.curRefresh.Timer;
document.all.curRefresh.Timer = 'On';
nTimeOut = nRefresh;
updateKnlButtons();
psStatusUpdate();
if (disable) disableButton();
}
Are you looking for
function refresh(nRefresh, disableButton) {
TimerSetting = document.all.curRefresh.Timer;
document.all.curRefresh.Timer = 'On';
nTimeOut = nRefresh;
updateKnlButtons();
psStatusUpdate();
disableButton();
}
function disableButton() {
idStopSelBtn.style.cursor='wait';
idStartSelBtn.style.cursor='wait';
idBounceRunningBtn.style.cursor='wait';
idStopAllBtn.style.cursor='wait';
idStartAllBtn.style.cursor='wait';
idBounceSelBtn.style.cursor='wait'
idStopSelBtn.src='images/Button/Disabled/Stop-Selected.gif';
idStartSelBtn.src='images/Button/Disabled/Start-Selected.gif';
idBounceRunningBtn.src='images/Button/Disabled/Bounce-Running.gif';
idStopAllBtn.src='images/Button/Disabled/Stop-All.gif';
idBounceSelBtn.src='images/Button/Disabled/Bounce-Selected.gif'
idStartAllBtn.src='images/Button/Disabled/Start-All.gif';
idStopSelBtn.onclick="return false";
}
refresh(5, disableButton);
I am playing around with a short little code to see if I can get a function going while the user has their mouse down and then end it when they bring their mouse up. For this example I am trying to increment a number that I am displaying on the screen as the user moves their mouse while holding the button down. I want it to freeze and stop once they release the button, however the counter just resets and the count continues from 0 even though the button is not being pressed...
function dragInit(state, e) {
var i = 0;
$(document).on("mousemove", function() {
if (state) {
i+=1;
$('#debug').text(i); //Show the value in a div
}
});
}
$(document).ready(function() {
$(document).on(
{mousedown: function(e) {
var state = true;
dragInit(e, state);
},
mouseup: function(e) {
var state = false;
dragInit(e, state);
}
});
});
As an aside, is there a way I can display whether a variable is true or false onscreen? When I try it just says [object Object].
There are a lot of mistakes in your code. I suggest you to read more basic concepts before starting to use jQuery.
The order of the parameters passed to dragInit() is wrong on both mouseup and mousedown event bindings.
The reason your counter is restarting is because your variable i is local, so it exists only during the function context it is declared in.
You are making the same mistake with the state variable, but in this case it is completely unnecessary to declare it.
Consider making your counter a global (even though it is not a good practice).
I can't provide you code because I am answering from my phone. A solution would be create a mousemove event that checkes whether the mouse button is pressed before incrementing your counter.
Hope I helped
You could do something like this:
function dragInit() {
$(document).on("mousemove", function () {
if (eventState.state) {
eventState.count += 1;
$('#debug').text(eventState.count); //Show the value in a div
}
});
}
// Create an object to track event variables
var eventState = {
count:0, //replaces your previous 'i' variable
state: false //keeps track of mouseup or mousedown
};
$(document).ready(function () {
$(document).on({
mousedown: function (e) {
eventState.state = true;
dragInit(); //don't need to pass anything anymore
},
mouseup: function (e) {
eventState.state = false;
dragInit(); //don't need to pass anything anymore
}
});
});
jsFiddle
Or keep everything together as one object
var dragInit = function () {
var count = 0;
var state = false;
var action = function () {
$(document).on("mousemove", function () {
if (state) {
count += 1;
$('#debug').text(count); //Show the value in a div
}
})
};
$(document).on({
mousedown: function (e) {
state = true;
action(); //don't need to pass anything anymore
},
mouseup: function (e) {
state = false;
action(); //don't need to pass anything anymore
}
});
}
$(document).ready(function () {
var obj = new dragInit();
});
jsFiddle 2
Example in response to comment
jsFiddle: This shows why the following code snippets differ in execution.
// Works
$(document).on("mousemove", function () {
if (state) {
}
})
// Doesn't
if (state) {
$(document).on("mousemove", function () {
});
}
Less code, You just need this.
Use jquery on and Off to turn on and off mousemove event.
Counter Reset http://jsfiddle.net/kRtEk/
$(document).ready(function () {
var i = 0;
$(document).on({
mousedown: function (e) {
$(document).on("mousemove", function () {
$('#debug').text(i++); //Show the value in a div
});
},
mouseup: function (e) {
i = 0;
$('#debug').text(i);
$(document).off("mousemove");
}
});
});
W/O Reset http://jsfiddle.net/gumwj/
$(document).ready(function () {
var i = 0;
$(document).on({
mousedown: function (e) {
$(document).on("mousemove", function () {
$('#debug').text(i++); //Show the value in a div
});
},
mouseup: function (e) {
$(document).off("mousemove");
}
});
});
WithNoCounter http://jsfiddle.net/F3ESx/
$(document).ready(function () {
$(document).on({
mousedown: function (e) {
$(document).on("mousemove", function () {
$('#debug').data('idx',parseInt($('#debug').data('idx')|0)+1).text($('#debug').data('idx')); //Show the value in a div
});
},
mouseup: function (e) {
$(document).off("mousemove");
}
});
});
Assuming you are married to Jquery (nothing wrong with that) - check out and consider entirely re-thinking your approach leveraging the ".one()" (http://api.jquery.com/one/) method.
edit: and if that taste doesn't sit well - familiarize yourself with the "deferred" object (http://api.jquery.com/category/deferred-object/)
lots of ways to approach this via jquery - what you decide in the end depends on what you really intend to do with this.