Whenever I click on "add JavaScript", the action programmed is executed, but the page reloads. I just want to add a link on a div and show it on screen.
Someone knows why?
window.onload = function(){
var adicionar = document.getElementById("adicionar");
adicionar.onclick = function(){
add();
}
};
function add(){
var div = document.getElementById("link-meio");
var novoLink = document.createElement('A');
var novoTexto = document.createTextNode("Novo textoooo");
novoLink.appendChild(novoTexto);
div.appendChild(novoLink);
}
#adicionar must be an anchor tag. You can return false from your click handler to disable the default behaviour of the click on an anchor tag (which is to load the page corresponding to the href attribute, and will cause the current page to reload if the href is empty).
Its is caused by the default event is triggered when you do click on the a element with id "adicionar", you could call the preventDefault method before, like this
window.onload = function(){
var adicionar = document.getElementById("adicionar");
adicionar.onclick = function(e){
e.preventDefault();
add();
}
};
function add(){
var div = document.getElementById("link-meio");
var novoLink = document.createElement('A');
var novoTexto = document.createTextNode("Novo textoooo");
novoLink.appendChild(novoTexto);
div.appendChild(novoLink);
}
Related
I am trying to set up a button that on click will redirect to a new link. I have tried so many different options and I just cannot get it to work.
var button = document.createElement("button");
button.innerHTML = "$1.00";
divInnerElement.appendChild(button);
button.addEventListener ("click", function() {
window.location('http://www.google.com','_blank');
return false;
});
Update: The function works but it only reloads the current page vs redirecting you to different page. If I use window.open it works but I dont want it to open a new window.
Update:
So I am not sure what was causing the click when using window.location but I was able to add an aTag into the button and that then resolved the problem.
<script>
var button = document.createElement("button");
var aTag = document.createElement('a');
aTag.setAttribute('href','http://www.google.com');
aTag.innerHTML = '$1.00';
button.appendChild(aTag);
divInnerElement.appendChild(button);
// button.addEventListener ("click", function() {
// window.location.href = 'http://www.google.com';
// return false;
// });
</script>
Your question is very vague, Here is some working code- hope it's what you need
Html:
<div id="divInnerElement"></div>
Javascript:
var button = document.createElement("button");
button.innerHTML = "$1.00";
document.getElementById('divInnerElement').appendChild(button);
button.addEventListener ("click", function() {
window.open('http://www.google.com','_blank');
return false;
});
I used window.open: since you put in your original snippet _blank, I'm assuming you would like to open the link in a new tab.
This code snippet should be in bottom of the page and remove the return statement from code so that page will be open in new tab.
var button = document.createElement("button");
button.innerHTML = "$1.00";
document.getElementById('divInnerElement').appendChild(button);
button.addEventListener ("click", function() {
window.open('http://www.google.com','_blank');
});
So I am not sure what was causing the click when using window.location but I was able to add an aTag into the button and that then resolved the problem.
<script>
var button = document.createElement("button");
var aTag = document.createElement('a');
aTag.setAttribute('href','http://www.google.com');
aTag.innerHTML = '$1.00';
button.appendChild(aTag);
divInnerElement.appendChild(button);
// button.addEventListener ("click", function() {
// window.location.href = 'http://www.google.com';
// return false;
// });
</script>
First of all this is against accessibility and kind of deceiving to the user based on the html elements being used on the page for their functionality. In your case if the user is being navigated to another page it should be created as an anchor element instead of button IMO. If you need the look of a button for it just use css to style it accordingly.
In brief this could be because the script is executed before the page loads. Try and move the script to the bottom of the page.
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 am trying to send the text typed in to a box via a link. Please see my code below. It isn't sending through for some reason?
<script>
var discountCode = document.getElementById("discountCode").value;
openPage = function() {
location.href = "payment.php?discount="+discountCode;
}
</script>
Purchase
You're reading the value as soon as the page loads, not when the link is clicked. You just need to move the line into the function:
<script>
openPage = function() {
var discountCode = document.getElementById("discountCode").value;
location.href = "payment.php?discount="+discountCode;
}
</script>
Purchase
Or alternatively just get a reference to the element when the page loads (assuming this script is after the discountCode element), then read the value in the function:
<script>
var discountCode = document.getElementById("discountCode");
openPage = function() {
location.href = "payment.php?discount="+discountCode.value;
}
</script>
Purchase
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
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);