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.
Related
I am doing one feature about showing alert on external link(apart from current domain) click. For that, I have written below code. All is working fine except below scenario.
$('a').each(function() {
var $a = jQuery(this);
if ($a.get(0).hostname && getDomain($a.get(0).hostname) != currentDomain) {
$a.click(function(event) {
//console.log($a.get(0));
//var myClasses = this.classList;
//console.log(myClasses.length + " " + myClasses['0']);
$("#redirectconfirm-modal").removeClass('hide');
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
$modal.on('show', function() {
$modal.find('.btn-continue').click(function() {
confirmed = true;
$a.get(0).click();
$modal.modal('hide');
location.reload();
});
});
$modal.on('hide', function() {
$a.get(0).removeClass("selected");
confirmed = false;
});
$modal.modal('show');
}
});
}
});
Scenario which produces this issue:
Click on any external link from the site, it open a modal popup for redirection confirmation with continue & return button.
If I click on "Return" button it closes the modal popup.
Now, I am clicking on external link from my site, it open the modal again but this time I am clicking on "Continue" button & guess what, it open that external link in 3 different tabs
Actually on each anchor tag click, it saves whole anchor tag value. I think, if remove all these anchor tag values on modal close code i.e. $modal.on('hide', function() { }) it will resolve problem. I had tried with many different ways but still facing this issue.
Can you please provide solution/suggestion on that?
Problem is when you have 3 external links (as you probably have), than you set 3 times this part of code:
$modal.on('show', function() { ... });
$modal.on('hide', function() { ... });
which is wrong. Those events listeners should be set only once.
Some simplified code would look like this:
var $modal = $("#redirectconfirm-modal");
var currentDomain = 'blabla';
$modal.on('click', '.btn-continue', function(e) {
window.location = $modal.data('redirectTo');
});
$('a').each(function() {
var $a = jQuery(this);
if( $a.get(0).hostname && getDomain($a.get(0).hostname)!=currentDomain ) {
$a.click(function(e) {
$modal.data('redirectTo', $a.attr('href'));
$modal.modal('show');
});
};
});
Don't inline your events, you may try something like this:
$('a').each(function() { //add a class to all external links
var $a = jQuery(this);
if ($a.get(0).hostname && getDomain($a.get(0).hostname) != currentDomain) {
$a.addClass('modalOpen');
}
});
$('.modalOpen').not(".selected").click(function(event) { //open the modal if you click on a external link
event.preventDefault();
$('.modalOpen').addClass('selected'); //add class selected to it
$modal.modal('show');
});
$modal.on('hide', function() {
$('.selected').removeClass("selected");//remove the class if you close the modal
});
$('.btn-continue').click(function() {
$('.selected').click();//if the users clicks on continue open the external link and hide the modal
$modal.modal('hide');
});
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 dynamically add a button to a page on a third-party website, and add a click handler to the button, using a Chrome extension. I have read onClick within Chrome Extension not working, added the handler in a separate js file.
The problem is that Chrome tries to find that js file in the web server, not in the extension. So, 404 happens.
Let's say the web page is "http://www.somecompany.com/somepage.html". My extension code is like the following.
var aButton = document.createElement('button');
aButton.id = "aButton";
thatDiv.appendChild(aButton);
var aScript = document.createElement("script");
aScript.src="aButtonHandler.js";
thatDiv.appendChild(aScript);
Chrome tries to load "http://www.somecompany.com/aButtonHandler.js", and of course the real web site does not have that script, so 404 happens. How can I add a button to a web site and execute alert("hello"); when the button is clicked?
Added
I added the code in aButtonHandler.js to the end of the content script itself, but nothing happened. What is wrong?
content script.js
addButton();
function addButton()
{
//adds a button by the code above.
}
document.addEventListener('DOMContentLoaded', function() {
var theButton = document.getElementById('aButton');
theButton.addEventListener('click', function() {
alert('damn');
});
});
Added
This worked.
content script.js
addButton();
function addButton()
{
//adds a button by the code above.
aButton.addEventListener('click', function() {
alert('damn');
});
}
Using the setInterval function to check <button> element is exists, if not create and append the <button> element.
var myVar = setInterval(function() {
if(document.getElementById('aButton')) {
// clearInterval(myVar);
return false;
} else {
if(document.getElementsByClassName("assignedToUsers")[0]) {
var button = document.createElement("button");
button.innerHTML = "Test";
button.id = "aButton";
button.type = "button";
document.getElementsByClassName("assignedToUsers")[0].appendChild(button);
var theButton = document.getElementById('aButton');
theButton.addEventListener('click', function() {
console.log(document.getElementsByClassName("ms-TextField-field")[0].value);
});
}
}
}, 500);
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);
}
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