Track a button onclick event - javascript

I have a script that tracks outgoing links when the link is inside an <a> tag.
The script is from here
The script will track html inside the tag or an image.
What I need is for it to track a button as seen below.
Here is the code I guess I need to modify:
function clicktracker(e)
{
var ie = navigator.appName == "Microsoft Internet Explorer";
var src = ie ? window.event.srcElement : e.target;
var tag = (src.tagName.toLowerCase() != "a") ? src.parentNode : src;
if (!tag || tag.tagName.toLowerCase() != "a") return;
domain = clicktracker_domain (tag.href);
extension = clicktracker_extension(tag.href);
if ( clicktracker_inarray(clicktracker_domains, domain) &&
!clicktracker_inarray(clicktracker_extensions, extension)) return;
var url = tag.href;
var title = '';
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.innerHTML);
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.title);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt(src.alt);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt("Image");
url = escape(url .substr(0, 150));
title = escape(title.substr(0, 150));
if (url && title) setTimeout("clicktracker_aux('"+url+"', '"+title+"')", 10);
return;
}
Here is the button I want to track
<button type="button" title="title" style="background:#cda85c;" class="button btn-cart" onclick="window.open('http://www.example.com')"><span><span><?php echo $this->__('Buy Now') ?></span></span></button>
Here is the full script:
function clicktracker_inarray (arr, val)
{
for (var i in arr) if (arr[i] == val) return true;
return false;
}
// ***** clicktracker_innertxt *****
function clicktracker_innertxt(str)
{
str = str.replace(/<[^>]*>/g, ' ');
str = str.replace( /&/g, '&');
str = str.replace( / /g, ' ');
str = str.replace( /^\s+/g, '');
str = str.replace( /\s+$/g, '');
return str;
}
// ***** URL *******************************************************************
var clicktracker_re_scheme = "^\\w+://";
var clicktracker_re_folder = "((?:-|\\w|\\.)*)";
var clicktracker_re_domain = clicktracker_re_scheme+ clicktracker_re_folder;
var clicktracker_re_urlall = clicktracker_re_domain+"(?:/"+clicktracker_re_folder+')*';
// ***** clicktracker_domain *****
function clicktracker_domain(url)
{
var reg = new RegExp(clicktracker_re_domain);
var match = reg.exec(url);
if (!match) return "";
match = match[match.length-1];
return match;
}
// ***** clicktracker_extension *****
function clicktracker_extension(url)
{
var reg = new RegExp(clicktracker_re_urlall);
var match = reg.exec(url);
if (!match) return "";
match = match[match.length-1].split(".");
return (match.length >= 2) ? match[match.length-1] : "";
}
// ***** Track *****************************************************************
// ***** clicktracker_aux *****
function clicktracker_aux(url, title)
{
var img = new Image();
img.src = clicktracker_url+"?url="+url+"&title="+title+"&rand="+Math.random();
}
// ***** clicktracker *****
function clicktracker(e)
{
var ie = navigator.appName == "Microsoft Internet Explorer";
var src = ie ? window.event.srcElement : e.target;
var tag = (src.tagName.toLowerCase() != "a") ? src.parentNode : src;
if (!tag || tag.tagName.toLowerCase() != "a") return;
domain = clicktracker_domain (tag.href);
extension = clicktracker_extension(tag.href);
if ( clicktracker_inarray(clicktracker_domains, domain) &&
!clicktracker_inarray(clicktracker_extensions, extension)) return;
var url = tag.href;
var title = '';
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.innerHTML);
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.title);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt(src.alt);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt("Image");
url = escape(url .substr(0, 150));
title = escape(title.substr(0, 150));
if (url && title) setTimeout("clicktracker_aux('"+url+"', '"+title+"')", 10);
return;
}
// ***** Attach Events *********************************************************
if (navigator.appName == "Microsoft Internet Explorer")
document.attachEvent ('onclick', clicktracker);
else document.addEventListener('click', clicktracker, false);
edit*****
The clicks are then stored in the database and called for from a php page.

There's a lot going on in those scripts and it's not clear what you mean by "track", so I'll just give a short version:
document.addEventListener('click',function(e){
var tag=e.target.tagName.toLowerCase();
switch(tag){
case "a":
//use e.target to track this link event
break;
case "img":
//use e.target to track this image event
break;
case "button":
//use e.target to track this button event
break;
}
});
This listens for clicks anywhere on the page, and you use e.target to inspect the click.
Edit:
e is just the name I gave to the event object, which is automatically passed into the function by the event listener. One of the properties that's always in this object is target which contains a bunch of info about the event. if you drop console.log(e) inside the function in the event listener above, you can pull it up in Chrome, hit control+shift+i, go to the javascript console, and explore what's in there.

Related

Script does not jump to the next field when the maxlength is reached

This is my script
<script>
var InputContainer = document.getElementsByClassName("InputContainer")[0];
container.onkeyup = function(e) {
var target = e.srcElement || e.target;
var maxLength = parseInt(target.attributes["maxlength"].value, 10);
var myLength = target.value.length;
if (myLength >= maxLength) {
var next = target;
while (next = next.nextElementSibling) {
if (next == null)
break;
if (next.tagName.toLowerCase() === "input") {
next.focus();
break;
}
}
}
// Move to previous field if empty (user pressed backspace)
else if (myLength === 0) {
var previous = target;
while (previous = previous.previousElementSibling) {
if (previous == null)
break;
if (previous.tagName.toLowerCase() === "input") {
previous.focus();
break;
}
}
}
}
</script>
I have also put a around the entire form.
You can find the original webpage at: https://im-here.biz/ContactForm/contact-inc.php
Obviously, I am doing something wrong here.
Ideas?
I can see an error in the console on the above-mentioned URL. By seeing your code there is no container defined. I guess you should be using InputContainer instead of the container variable or change the declaration like this:
<script defer>
// Put your code here
var container = document.getElementsByClassName("InputContainer")[0];
</script>

Activating script via keypress using JS

I am trying to modify a WordPress plugin which activates a game script when a button is pressed. I would like to be able to activate it with a combination of key presses instead (Shift + Control + F).
I have attempted wrapping the entire script in a keypress function, however, this did not work. I have confirmed that script is loaded via console log but pressing the key combination does not do anything.
Original code:
PHP
<?php
...
/* Insert the button*/
switch ($asteroids_buttonopt) {
case "push-1":
echo '<div><p style="text-align: center;">
<a href="#" onclick="'.$asteroids_start.'"><button>Click to Play Asteroids!!!</button>
</a></p></div>';
break;
...
}
?>
JS
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function startAsteroids(color,address) {
var ver = getInternetExplorerVersion();
if(ver>=0){
color = typeof(color) != 'undefined' ? color : 'black';
document.onkeydown = function(ev) {
var key;
ev = ev || event;
key = ev.keyCode;
if(key == 37 || key == 38 || key == 39 || key == 40) {
//e.cancelBubble is supported by IE - this will kill the bubbling process.
ev.cancelBubble = true;
ev.returnValue = false;
}
}
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
else{
color = typeof(color) != 'undefined' ? color : 'black';
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
}
Any help would be greatly appreciated. The original plugin 'Asteroid Widget' was abandoned 8 years ago so I cannot seek help from the developers.
Instead of wrapping the entire page content, you should add the following onkeypress function to the end of the JS file.
Required Function
window.onkeypress=function(e){
if(e.ctrlKey && e.shiftKey && e.code==='KeyF' ){
startAsteroids('','/wp-content/plugins/asteroids-widget/gears/play-asteroids-yellow.min.js');
}
}
Complete resulting file
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function startAsteroids(color,address) {
var ver = getInternetExplorerVersion();
if(ver>=0){
color = typeof(color) != 'undefined' ? color : 'black';
document.onkeydown = function(ev) {
var key;
ev = ev || event;
key = ev.keyCode;
if(key == 37 || key == 38 || key == 39 || key == 40) {
//e.cancelBubble is supported by IE - this will kill the bubbling process.
ev.cancelBubble = true;
ev.returnValue = false;
}
}
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
else{
color = typeof(color) != 'undefined' ? color : 'black';
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
}
window.onkeypress=function(e){
if(e.ctrlKey && e.shiftKey && e.code==='KeyF' ){
startAsteroids('','/wp-content/plugins/asteroids-widget/gears/play-asteroids-yellow.min.js');
}
}

how to logout user when tab/browser is closed?

Applied onbeforeunload in body tag to logout user when a tab/browser is closed in an MVC Application.
I somehow managed to bypass redirecting to other links and also F5, but when I click on refresh button it logs me out, also when I select url in address bar and hit enter it logs me out.
<body onbeforeunload="UserLogoutOnBrowserClose(event)">
<script>
var href;
var id;
var logout;
var descargar;
var isF5Pressed;
$('a').click(function () {
href = ($(this).attr('href'));
id = ($(this).attr('id'));
if (id === "logout")
logout = id;
else if (id === "descargar")
descargar = id;
});
$(document.body).on("keydown", this, function (event) {
if (event.keyCode == 116) {
isF5Pressed = true;
}
});
$(window).on("unload", this, function (event) {
console.log(window.performance);
});
function UserLogoutOnBrowserClose(e) {
debugger;
var navigation = e.currentTarget.performance.navigation.type;
var activeElement = document.activeElement;
var myWindow;
var Uri = '#Url.Action("LogOff", "Account",new { area="" })';
var bodyID = '#bodyId';
var attributes = document.activeElement.attributes;
var attributesId = (document.activeElement.attributes).id;
var baseURI = document.baseURI;
// submit-pse-button check is applied to prevent user from signing out while redirecting to PSE portal
if (attributesId.value === "submit-pse-button" || attributesId.value === "reclamarButton" || activeElement.localName === "a"
|| activeElement.localName === "button" || logout != undefined || descargar != undefined || isF5Pressed != undefined) { }
else {
if (attributes.href != undefined) {
if (bodyID === "customer" && baseURI == attributes.href.value)
myWindow = window.open(Uri, "");
}
else {
if (bodyID === "customer")
myWindow = window.open(Uri, "");
}
}
}
</script>
How to bypass all other events like form submits, anchor tag clicking, button pressing input submits to have this event fired or at least can check if any of the above is clicked/hit/submitted.

Return a variable to use as image src

I have a variable image that needs to display based on another form field so if the first form field says XYZ123 then the picture I need displayed will be in the server filesystem already and named XYZ123.jpg
I can't work out the syntax to put it in
<td colspan=3 align="center"><img src="pictures/thumbnails/logo-20170820013631.jpg" alt="Logo" border=1 height=150 width=150></img><br>Click to enlarge.</td>
This works fine if I use a static image name, but I need dynamic
I have a function that is called whenever the first field is changed
<div><b>EDIT CUSTOMER DETAILS</b><br><input type="text" name="key" onchange="changedReference(this.name);" placeholder="enter customer ID"></div> //calls function
function changedReference(n)
{
var ref = EL(n).value;
var img = EL(n).value;
if (ref == null || ref == "") return;
var x = getXmlHttpRequest();
if (x == null) {
alert("Unable to get XmlHttpRequest");
return;
}
var u = "card-get.php?reference=" + encodeURI(ref);
x.open("GET", u, false);
x.send();
var t = x.responseText;
if (t == null || t.indexOf('=') < 0) {
alert("Unknown Customer ID [" + ref + "]");
return;
}
var ra = t.split("\n");
var lookup = new Object();
for (var i = 0; i < ra.length; i++) {
var pos = ra[i].indexOf('=');
if (pos < 0 || pos == 0) continue;
var en = ra[i].substring(0, pos);
var ev = ra[i].substring(pos + 1);
if ((en == "dob" || en == "id1_expiry") && ev.length == 10 && ev.indexOf("-") >= 0) {
ev = ev.substring(8, 10) + "/" + ev.substring(5, 7) + "/" + ev.substring(0, 4);
}
var e = EL(en);
if (e != null) e.value = ev;
}
}
so var img holds the value I need without the .jpg now I need it to display but am lost trying to make it happen.
Give the image tag in your html an id like
<img id="changingImage" src="pictures/thumbnails/logo-20170820013631.jpg" />
Now you can change the image source to point to the filename inside your img variable...
document.getElementById('changingImage').src="pictures/thumbnails/"+img+".jpg";

Trigger alert function event for text area node in Firefox Javascript XUL

I want to trigger an alert if the user reached max number of characters in the text area.
Generally my plugin fill the user node values directly to my plugin text box. So, I want to generate an alert if the user reached var mymaxlength = 20;
var mymaxlength = 20;
if ( nodeName == "textarea" && node.value.length >= mymaxlength ) {
// call your popup / alert function
alert('hi, you have reached 20 characters');
}
I have tried the above code, it didn't work without any errors? In my full code, the general alert is working but the alert inside the loop is not working?
1. Is it a good way of triggering an alert in onKeypress : function (e)? or
2. Would it be possible to trigger an alert if the user node has filed 20 characters in the fillText : function (node)?
Please assist me!
This is the full code:
run : function () {
//alert(content.document.cookie);
//alert("-"+content.document.cookie+"-");
var cookieTest = content.document.cookie
var JSESSIONID = pdees.get_Cookie("JSESSIONID");
if(verifyConnection){
if(JSESSIONID && cookieTest){
//var result = verifyUserIdentity(JSESSIONID);
var head = content.document.getElementsByTagName("head")[0];
var body = content.document.body;
//var style = content.document.getElementById("pdees-style");
//var allLinks = content.document.getElementsByTagName("pdees");
var foundLinks = 0;
//extract text element from body
if(document.getElementById && document.createTreeWalker && typeof NodeFilter!="undefined"){
var tw=document.createTreeWalker(body,NodeFilter.SHOW_TEXT,null,false);
lookForpdees(tw);
}
addJScode();
idpdeesbutton=0;
}else{
alert("You should connect to the Application Environment to be authentified");
}
}else{
//var result = verifyUserIdentity(JSESSIONID);
var head = content.document.getElementsByTagName("head")[0];
var body = content.document.body;
//var style = content.document.getElementById("pdees-style");
//var allLinks = content.document.getElementsByTagName("pdees");
var foundLinks = 0;
//extract text element from body
if(document.getElementById && document.createTreeWalker && typeof NodeFilter!="undefined"){
var tw=document.createTreeWalker(body,NodeFilter.SHOW_TEXT,null,false);
lookForpdees(tw);
}
addJScode();
idpdeesbutton=0;
}
},
onKeypress : function (e) {
var mymaxlength = 20;
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//text area cache onKeyPress code
//alert('hi1');
if ( nodeName == "textarea" && node.value == "" && e.keyCode == 13 ) {
pdees.fillText(node);
return;
}
if ( nodeName == "textarea" && node.value.length >= mymaxlength ) {
// call your popup / alert function
alert('hi, you have reached 20 characters');
}
// this node is a WYSIWYG editor or an editable node?
if ( ( nodeName != "html" || node.ownerDocument.designMode != "on" ) && node.contentEditable != "true" )
return;
if ( node.textContent == "" && e.keyCode == 13 ) {
pdees.fillText(node);
return;
}
if (!node.tacacheOnSave) {
pdees.fillText(node);
}
},
onChange : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//alert("onChange : "+nodeName);
if ( nodeName != "textarea" )
return;
pdees.fillText(node);
},
onInput : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//alert("onInput : "+nodeName);
// Only for textarea node
if ( node.nodeName.toLowerCase() != "textarea" )
return;
if ( node.value == "" )
return;
pdees.fillText(node);
},
fillText : function (node) {
nodeSRC = node;
if ( node.nodeName.toLowerCase() == "textarea" )
{
//alert('hi');
userContent = node.value;
//alert(userContent);
}
else if ( node.nodeName.toLowerCase() == "html" ) {
userContent = node.ownerDocument.body.innerHTML;
//alert(userContent);}
}
else // element.contentEditable == true
userContent = node.innerHTML;
},
emptyNodeSRC : function (node){
if ( node.nodeName.toLowerCase() == "textarea" ) {
node.value = "";
}
else if ( node.nodeName.toLowerCase() == "html" ) {
node.ownerDocument.body.innerHTML = "";
}
else // element.contentEditable == true
node.innerHTML = "";
},
};
}();
Finally, I have found my problem and I have succeed to trigger mu custom alert:
In this function fillText : function (node)where I can trigger an alert for the userContent. So I made a length and triggered an alert for it.
else if ( node.nodeName.toLowerCase() == "html" ) {
userContent = node.ownerDocument.body.innerHTML;
//alert(userContent);
var myTest = userContent.length;
if(userContent.length == 30)
{
alert('Hi, there!');
}
}
else // element.contentEditable == true
userContent = node.innerHTML;
},
Note: For complete code please refer to my question.

Categories