My goal is to store the total amount of clicks on links in a certain page into a variable and recall that variable when the user exits the page. Would this be a correct way of doing it?
window.onunload = function(){
alert("Total Links Clicked:" + clicks(););
}
var clicks = function(){
var clickArray = [];
var getLinks = document.getElementsByTagName(A);
var clickValue = getLinks.onclick = function() {
clickArray.push("1");
}
var totalClicks = clickArray.length;
return totalClicks;
}
Your code won't work for several reasons:
You bind the click handler in clicks() function and don't call clicks() until the page is unloaded, at which point it is too late to handle any clicks. You need to bind the click handler when the page loads.
You can't set .onclick on a list of elements, which is what your getLinks variable is given it was set to the result of getElementsByTagName() (get elements not get element).
You pass an undeclared variable A to getElementsByTagName(); you should pass the string "a".
You have a semicolon inside the alert()'s closing ), which is a syntax error.
You could try something like this:
window.onload = function() {
var clicks = 0;
window.onunload = function(){
alert("Total Links Clicked:" + clicks);
}
function clicked() {
clicks++;
}
var getLinks = document.getElementsByTagName("a");
for (var i = 0; i < getLinks.length; i++)
getLinks[i].onclick = clicked;
};
Note that the browser may block an alert() during an unload event, but if you use console.log() instead you can see that clicks had the right value.
Note also that of course a click on a link to another page will cause an unload, so the click count will only be more than 1 if you have links within the current page.
Demo: http://jsfiddle.net/A3bkT/1/
You can use sessionStorage or localStorage for that.
if(typeof(Storage)!=="undefined")
{
// store the clicks here
sessionStorage.numClicks = value;
}
and read more on these two here : http://www.w3schools.com/html/html5_webstorage.asp
Bind a global event listener and just store the count with sessionStorage:
var clicks = 0;
document.addEventListener('click', function(event) {
if (event.target.nodeName == 'A') {
window.sessionStorage.setItem('clicks', ++clicks);
}
}, false);
Related
I have below line of code which simply places a link on the parent page:
<caps:msg textId="createNews"/>
Onclick of the above link 2 functions are getting called:
###func1():
var timestamp;
function func1() {
timestamp = +new Date();
return false;
}
###func2():
function func2(param1,param2,param3,param4){
var win;
var location = window.location.href; // location A
var encodeStringVar = encodeString(param3);
win = window.open(param1+'/struts1.action?param2='+param2+'¶m3='+ escape(encodeStringVar) +'#'+param4,target='t1','toolbar=no,scrollbars=yes,menubar=no,location=no,width=990,height=630, top=100, left=100');
window.location.href = location; // location A
return win;
}
On click of link on parent page, a popup opens by calling struts action, and it works just fine. Only problem is when the link on parent page is clicked, it refreshes the parent page. I don't want it to refresh and I tried adding return false in the link and Javascript void() function, Also I tried by adding an event listener for click event on this link as below:
$(document).ready(function() {
$("#createNewsLink").click(function(event) {
//return false;
event.preventDefault();
})
})
and below:
$(document).ready(function() {
document.getElementById("createNewsLink").addEventListener("click", function(event) {
event.preventDefault();
});
})
But none of these did the trick, can someone please point out the mistake in my code?
Could you consider to try :
(function(){
var linkElement = document.querySelector('#createNewsLink');
linkElement.addEventListener('click',function(e) {
var param1 = e.target.getAttribute('attr-param1');
var param2 = e.target.getAttribute('attr-param2');
console.log(param1,param2);
// Do what ever you want here.
e.preventDefault();
});
})();
Click me
Here i avoid any Event binding from html, and centralize all traitment / binding in one place. Then i point one way to find back mandatory params for your traitment.
I'm adding a click event to all links that match a particular selector as part of a JS module I'm creating. It looks something like this.
var Lightbox = (function () {
var showLightbox = function () {
// this does stuff
};
var init = function () {
var links = document.querySelectorAll(options.selector);
for(var i = 0; i < links.length; i++) {
links[i].addEventListener('click', function() {
showLightbox();
}, false);
}
};
return {
init: init
};
})();
Lightbox.init();
On first load the any links on the page that match the selector work. There is also a closeLightbox() method that works fine. However when clicking the links for a second time nothing happens. I get no console errors – nuffin.
Is there something I'm doing wrong when adding the event listener?
EDIT: I've updated the code to remove some redundant methods and have pasted the full code here: http://pastebin.com/mC8pSAV2
You are reassigning innerHTML of the whole document:
document.body.innerHTML += response;
on the link click. That wipes out all existing DOM elements with their events and creates new DOM structure with no clicks assigned.
I am calling a pop up window from a parent page using :
var childWindow = open('test1.aspx', '1397127848655', 'resizable=no,width=700,height=500');
I then try to set the value of two spans which are on chil pop up from parent window using this childWindow object.
childWindow.onload = function () {
alert('this msg does not shows up when run on IE8');
var hidden1 = childWindow.document.getElementById('hidden1');
var hidden2 = childWindow.document.getElementById('hidden2');
hidden1.innerHTML = rowindex;
hidden2.innerHTML = controlname;
};
this code works fine as long as I am using chrome. But it refuses to work on IE8. There are no console errors either.
I tried removing childWindow.onload = function () { } but then the page would just sort of refresh on both chrome and IE8.
UPDATE
This did not work either.
function CallPopUp(rowindex,controlname ) {
function popupLoad() {
alert('this msg does not shows up when run on IE8');
var hidden1 = childWindow.document.getElementById('hidden1');
var hidden2 = childWindow.document.getElementById('hidden2');
hidden1.innerHTML = rowindex;
hidden2.innerHTML = controlname;
}
var childWindow = open('test1.aspx', '1397127848655', 'resizable=no,width=700,height=500');
if (childWindow.document.readyState === "complete") {
popupLoad();
} else {
childWindow.onload = popupLoad;
}
If test.aspx is in the browser cache, it is possible that the onload event has already happened before you attach your event handler so you're missing it (IE is known to do this with image load events). I'd suggest you check document.readyState before attaching your event handler.
function popupLoad() {
alert('this msg does not shows up when run on IE8');
var hidden1 = childWindow.document.getElementById('hidden1');
var hidden2 = childWindow.document.getElementById('hidden2');
hidden1.innerHTML = rowindex;
hidden2.innerHTML = controlname;
}
var childWindow = open('test1.aspx', '1397127848655', 'resizable=no,width=700,height=500');
if (childWindow.document.readyState === "complete") {
popupLoad();
} else {
childWindow.onload = popupLoad;
}
As another option, you can put the values into the query parameters for the URL:
`"test1.aspx?hidden1=" + rowindex + "&hidden2=" + controlname`
and then have the popup window load it's own fields from it's own onload handler from what's in the query string. Then, you can keep the code in the popup window self contained and you don't have to try to modify one window from another.
If you don't want the user to see this or be able to edit it, you can turn off the location bar in the popup window.
I have a clickable image that when you click a modal popup appears. I want to make sure you can only click it once and while the popup is showing, the clickable image is unclickable. I've tried several methods but no solution works as I want it to.
Here is the code:
init: function () {
var myButton = document.getElementById("kaffePic");
var clickable = true;
console.log(clickable);
myButton.onclick = function(e) {
e.preventDefault();
console.log(clickable);
if(clickable)
{
clickable = false;
popup(myButton, clickable);
}
else
{
return false;
}
};
}
And here is a part of the popup window (removed some code that has nothing to do with the issue).
function popup(theButton, returnClick) {
var myDiv = document.createElement("div");
myDiv.className = "popupWindow";
var newButton = document.createElement('a');
var image = document.createElement('img');
image.src = 'img/theclosebutton.png';
image.className = "popupImage";
newButton.appendChild(image);
myDiv.appendChild(newButton);
newButton.onclick = function () {
document.body.removeChild(myDiv);
returnClick = true;
};
}
Right now I can click it once, and then never again.
Any suggestions?
it's called only once because clickable is set to false after the first click. i suspect you are trying to set it to true in your popup-method by calling returnClick = true; but all that does is setting your argument-value, not the actual clickable-variable itself.
right now, clickable is a variable in the scope of init, so popup can't access it. you could, for example, make clickable a var in the scope of init's parent object. then in popup, you'd access clickable by parentObject.clickable.
//illustration of my example
parentObject {
var clickable,
function init()
}
function popup() {
...
parentObject.clickable = true;
}
Check .one() event handler attachment of jquery and this the .one() of jquery is used to Attach a handler to an event for the elements. The handler is executed at most once per element per event type. second one is link to an stack overflow questions about resetting the .one().Hope this helps
Beginners Javascript question here.
I am trying to create a function that finds all the links in a given div and sets up an onclick event for each one. I can get the link hrefs correctly, but when I try using them in the onclick function, Javascript seems to only use the last value found:
I.E
I have these links
#purpose
#future
#faq
When I use the onclick function, every link is reported as the #faq link.
Here's the code:
function prepareLinks () {
var nav = document.getElementById('navigation');
var links = nav.getElementsByTagName ('a');
for (var i = 0; i<links.length; i++) {
var linkRef = links[i].getAttribute('href').split("#")[1];
links[i].onclick = function () {
var popUp = "You clicked the " +linkRef +" link";
alert (popUp);
}
}
}
Here you have a closure creation. External variable linkRef becomes saved in inner onclick function. Try this way:
clickFunction() {
var popUp = "You clicked the " + this.href.split("#")[1] +" link";
// this should mean current clicked element
alert (popUp);
}
for (var i = 0; i<links.length; i++) {
links[i].onclick = clickFunction;
}
This is a scoping problem. The expression "You clicked the " +linkRef +" link" is evaluated when the onclick event fires, but what is the value of linkRef at this point?
You're trying to attach a separate onClick handler to each link, but you're accidentally attaching the same one.
You could generate a new function each time by using the new Function() constructor as
links[i].onclick = new Function("","alert('You clicked the '"+linkRef+"' link');");
See http://tadhg.com/wp/2006/12/12/using-new-function-in-javascript/ for more details.
But it's generally better to see if you can have a single handler. It's interesting that when you get to an event handler, the "this" keyword refers to the generator of the event. So you could have your original code refer to this.getAttribute("href"). Too many handlers will make your javascript event processing slow.