Tracking multiple clicks on the same element - javascript

Looking for a way to track if an element has been clicked multiple times (for example, a user clicks "Submit" button several times to place an order).
We are doing some work redeveloping a website and in our UX research we found that people don't download PDFs from the site because the link behind the button is broken. We noticed that people tend to click the button several times before giving up, yet some still manage to download the PDF.
In order to show our changes to code have improved site performance and user experiences, we want to show that these "multiple clicks" have decreased.
Since the site uses Google Analytics, I have tried to create a variable in GTM that counts clicks on the same click element (which doesn't work):
function() {
var the_div = {{Click Element}};
var clickCount = 0;
return clickCount;
}
I expect the output to be a count of the times I've clicked on the Click Element (1, 2, 3, etc....)

Try like this.
Define a varable for count. and on each click increment it.
var i = 1;
$('#elem').on('click',function(){
console.log(i);
i++;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="elem">click here</div>

sorry for the delay in responding.
We found a solution.
As Piertstorff pointed out, the variable sets clickCount to zero every time it is called. The solution, was to build a custom HTML tag (that runs JS) - not a variable - that fires on a Page Load Trigger and listens for multiple clicks within a 2-second timeframe. The HTML tag then passes an event to the DataLayer and stored in a variable.
That variable (signalling multiple clicks occurred) activates a trigger for another tag that passes the {{Click Classes}} variable to GA

Use javascript variable with global scope
<script>
countClicks = 0;
function clickCountFunction() {
countClicks++;
}
</script>
Add onClick attribute in button and call clickCountFunction() in it

Related

Cloning Objects in Google Optimize

I'm trying to clone a button in Google Optimize (or any other javascript/jQuery method) that adds an item into a shopping cart. My problem is that when I run the code or experiment in Optimize, the button doesn't trigger.
Here's my two different attempts. Method 1 via Optimizes' interface.
Select the button to copy, use the 'edit code' to get the html.
Use Insert HTML a the location of the new button, and insert the code.
Version 2 uses jQuery's clone();
$('#SOME-ID > PATH TO THE ELEMENT TO CLONE').clone().attr('id', 'ADD-ID-FOR-GTM-TRACKING').appendTo('#proPriceMobile');
What could the problem be?
Thanks in advance!
It's quite possible, that your experiment fires BEFORE your buttons loads on your page, in your actual browser.
Do you get an error message in console?
My tip would be to wait for your button to load, before applying the DOM changes. If possible, do this all via JavaScript.
For example, here you can wait for an element to load, via using a callback and setTimeout():
// FUNCTION WHICH WAITS FOR YOUR INITAL BUTTON to LOAD
function waitForElement(className, callBack){
window.setTimeout(function(){
// GRAB YOUR ELEMENT
var element = document.querySelectorAll(className)[0];
if(element) {
callBack(className, element);
console.log("Callback successfully fired and code executed...")
} else {
waitForElement(className, callBack);
console.log("This runs every second until your element is loaded on the page..")
}
},1000)
};
// EXECUTE THE CODE IN THIS FUNCTION, WHEN YOUR BUTTON LOADS IN THE DOM
waitForElement(".your-element-classname",function(){
console.log("Button has loaded in DOM...");
// NOW CLONE YOUR BUTTON
});
When I've cloned buttons in the past, I've lost all functionality on the cloned button. So you may need to rebuild that functionality on the cloned button.

Can't simulate a click event with javascript in "web application"

I have searched a lot of information about this but have not found the solution yet.
My problem is the following, I am creating an extension to speed up the movement through several web pages, I have managed it with many of them, but I have come to some where I cannot simulate a click with Javascript and I don't know how to do it.
One of the pages is this: https://sports.betway.es/es/sports/in-play The page is in Spanish domain, therefore I do not know if they can access it from another country (without vpn), although I think that with domain ".com" it works.
The code is as follows, it's pretty simple.
var deportesActivos = document.getElementsByClassName("categoryListItemWrapper contentSelectorItemButton")
for(let i=0;i<deportesActivos.length;i++){
let nombre = deportesActivos[i].lastChild.firstChild.innerText
if(nombre == data.deporte){
deportesActivos[i].click()
}
}
deportesActivos I collect the DIV elements with that class from the page.
deportesActivos[i].lastChild.firstChild.innerText I extract the text of each element
if(nombre == data.deporte){
deportesActivos[i].click()
}
When it matches, click to enter the link.
The problem is that the click does not simulate me.
I have bought exactly the element that you click on, I have clicked manually and it works, I have tried to click on other elements of the web page and it does not work, I have tried to give a "listener on click" to the element and it does not work either.
The HTML of the page is as follows:Image with HTML Code of the website
I don't know if this helps but on website build with Ionic app neither works
The click event does not fully simulate a user click. It just fires the onClick handler on the element that you are targeting (and any parents).
If your are just redirecting to a new URL when the button is clicked, you could just do that in your loop instead.
// get the links, not the buttons
var deportesActivos = document.getElementsByClassName("categoryListItemWrapper contentSelector");
for (let i=0; i < deportesActivos.length; i++) {
// Drill down one extralevel to get the button text
let nombre = deportesActivos[i].firstChild.lastChild.firstChild.innerText;
if (nombre === data.deporte) {
// Redirect to the href in the link
window.location.href = deportesActivos[i].href;
}
}

javascript function reloads page upon completion

I have a simple javascript program that runs onclick of an image.
However, whenever I clicked the image, the page reloaded.
After a lot of debugging I found that the page doesn't reload until right as the script completes.
There are several setTimeouts in the code, but I noticed the page was reloading instantly. I even changed these timeouts to 15000 milliseconds, but it still reloads immediately.
I am using jquery, if it makes any difference.
I also want a different result from the program every time you click it, so that each time you click it a different script runs and a some text changes in a specific order. I did this by changing the onclick attribute of the images in each script to the name of the next script, so that script one would switch onclick to script two, and so on. I set a timeout on these switches so that one click doesn't race through every single script. script two isn't running, so that much works.
my code:
function getSounds() {
console.log("script. initiated");
$("#soundwebGetSoundDirections").html("Now, Wait until the file is done downloading and click below again.");
console.log("new message");
$("#soundwebGetSoundA").attr('href',"");
console.log("href eliminated");
setTimeout($("#soundwebGetSoundImg").attr('onclick','findFile()'),2000);
console.log("onclick to findFile()");
}
function findFile(){
console.log("FINDFILE")
$("#soundwebGetSoundDirections").html("Find the file(it's probably in your downloads), copy the path of the file (usually at the top of the file explorer) and paste in it the box below. Then, make sure there is a '/' at the end of the path and type 'Linkiness.txt' (case sensitive, without quotes) at the end. Once you have all that stuff typed, click the icon again.");
console.log("FIND IT, DARN IT!!");
$("#soundwebGetSoundPathInput").css("opacity",1);
console.log("diving into reader");
setTimeout($("#soundwebGetSoundImg").attr('onclick','readFile()'),1000);
}
function readFile(){
console.log("loading...");
$("#soundwebGetSoundDirections").html("loading...");
if(document.getElementById("soundwebGetSoundPathInput").value.length == 0){
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
}
}
and the HTML that's linked to,
<a id = "soundwebGetSoundA" href = "https://docs.google.com/feeds/download/documents/export/Export?id=1ynhHZihlL241FNZEar6ibzEdhHcWJ1qXKaxMUKM-DpE&exportFormat=txt">
<img onclick = "getSounds();" class = "soundwebImgResize" src = "https://cdn3.iconfinder.com/data/icons/glypho-music-and-sound/64/music-note-sound-circle-512.png" id = "soundwebGetSoundImg"/>
</a>
Thanks for any help,
Lucas N.
If you don't want clicking the image to cause the anchor tag to load the href, then move the image tag outside of the anchor tag.
You aren't using setTimeout correctly. You should be passing in a function not a statement. So, for example, instead of
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
you should use
setTimeout(function () { $("#soundwebGetSoundDirections").html("Please fill in Path!") },1000);
setTimeout(findFile,2000);
I think the same goes for setting the onclick attribute but I've never tried dynamically changing an onclick attribute like that.
Since you're already using jQuery you could try using .on('click'... and .off('click'... if your current setup isn't working.

RadScheduler update interval

I'm using RadScheduler for my project. In the scheduler, I need a periodical update, so in my javascript, I set interval for a method that call rebind() on the RadScheduler for every 60 seconds. The problem is that, when my user open the advanced form, the rebind() method makes the form disappear. How can I detect AdvancedForm opening and closing event so that I can stop /restart the timer ?
Thank you in advance.
While there is an event for when the RadScheduler opens its Edit form, called OnClientFormCreated, there is not one for when the edit form closes. There are ways to do this though, but you have do add some additional code.
When you think about it there are several different items that can lead to the form closing - the user can click on the close icon at the top right (or left, depending on your orientation) of the window, they can click cancel, or they can hit save.
Keeping that in mind, we can take a look at this demo, which shows the Advanced Edit Form in action, and also has some JavaScript pre-written for us.
Within the schedulerFormCreated() function we can do the following:
function schedulerFormCreated(scheduler, eventArgs) {
// Create a client-side object only for the advanced templates
var mode = eventArgs.get_mode();
if (mode == Telerik.Web.UI.SchedulerFormMode.AdvancedInsert ||
mode == Telerik.Web.UI.SchedulerFormMode.AdvancedEdit) {
// Initialize the client-side object for the advanced form
var formElement = eventArgs.get_formElement();
var cancelButton = $("[id$='_CancelButton']");
cancelButton.on("click", formClosed);
var templateKey = scheduler.get_id() + "_" + mode;
....
And then we have the formClosed event:
function formClosed(eventArgs) {
}
in formClosed you can just create your logic for resuming the timer, while in schedulerFormCreated you can directly call the function that stops the timer right after that if-statement.
In case you're wondering what we're doing here we're simply grabbing an instance of the jQuery object representing the element with an id that ends with _CancelButton (we're not interested in the beginning part) and then just binding to the click event using the .on() jQuery function.
To get an instance of the save button you just have to use _UpdateButton, and for the close icon it is _AdvancedEditCloseButton. Keep in mind that any element that ends with these substrings will be selected, so if you want to be more specific I recommend inspecting the elements of your advanced form using FireBug or the Chrome Dev tools to get their ID and plug that into the selector above.
This should allow you to get the functionality you're looking for.

Global Javascript link handler

Here's what I have:
A web application that runs in a single HTML page (call it myapp.req), with content coming and going via AJAX
The application can be entered externally with a link such as myapp.req?id=123, and the application opens a tab with the item at id 123
The content on the page is mostly user's content, and many times has inner-application links to myapp.req?id=123
The problem is that clicking a link to myapp.req?id=123 reloads the browser, and removes any content or state that the user had loaded
What I want is to be able to catch link clicks whose destination is myapp.req?id=123, and instead of reloading the page, just open the tab for item 123, leaving anything else currently loaded alone. If the link is for an external website, though, obviously just let the browser leave.
So my question really: Can I have a global link handler that checks if I want to handle the link click, and if so, run some Javascript and don't leave?
I understand I could find all <a>s and add listeners, but my hope is that the solution would only require setting up the listener once, and not adding link handlers every time new content is loaded on the page. Since content can be loaded many different ways, it would be cumbersome to add code to all those places.
Does that make sense?
jQuery's live is what you need:
$('a').live("click", function () {
var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
if (myID) {
//run code here
alert(myID);
return false;
}
});
Any link will now have this click handler whether it's been added after this is called or not.
Sure you can. Add a clickhandler on the body. So you catch all clicks. Then you have to check if the target of the event or one of its parent is a link with your specific href. In this case stop the event and open the tab.
updated to use .live instead of .click
If you use jQuery, you can add a "live" click event handler to every a href at once:
<body>
click here
<br/>
whatever
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$('a').live('click',function() {
var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
if (myID) {
//run code here
alert(myID);
return false;
}
});
</script>
This should extract the id from the href's query string and let you do whatever you want with it.

Categories