How can I select all a and form tags without needing to include jQuery?
I ultimately am trying to do the following:
$("a").click(function {
window.onbeforeunload = null;
});
$("form").submit(function {
window.onbeforeunload = null;
});
But I really would rather not include jQuery (or even Sizzle.js), if there's a more compact way to do that.
You can use document.querySelectorAll() like this:
var els = document.querySelectorAll( 'a' );
for( var i=els.length; i--; ) {
els[i].addEventListener( 'click', function(){ window.onbeforeunload = null; } );
}
Similar for the <form> tags.
It is available in most modern browsers (caniuse.com).
This should do it:
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("click", function() { console.log("Clicked"); window.onbeforeunload = null; });
}
To get the form submit, you can do something like this:
<script>
do_function() { window.onbeforeunload = null; }
</script>
<form action="" onsubmit="do_function()" method="">
EDIT:
To combine the two:
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("click", function() { console.log("Clicked"); window.onbeforeunload = null; });
}
var forms = document.getElementsByTagName("form");
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener("submit", function() { console.log("Submitted"); window.onbeforeunload = null; });
}
Fiddle
Related
I am not very good with javascript codes so if someone can help me I would appreciate it
I'm trying to hide all the elements "Button" after use innerHTML. My current code is this below and I can not figure out how to make it work.
<script>
function print() {
var content = document.getElementById('search_result').innerHTML;
new_page = window.open('about:blank');
new_page.document.write(content);
new_page.window.print();
new_page.window.close();
}
</script>
<script>
function print() {
var content = document.getElementById('search_result');
setButtonsDisplay(content, 'none');
new_page = window.open('about:blank');
new_page.document.write(content.innerHTML);
setButtonsDisplay(content, '');
new_page.window.print();
new_page.window.close();
}
function setButtonsDisplay (elm, prop) {
var btns = elm.getElementsByTagName('button');
for (var i = 0; i < btns.length; i++) {
btns[i].style.display = prop;
}
}
</script>
An alert should display anchor's zero-based index within a document instead of following the link.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test page</title>
</head>
<body>
In my life, I used the following web search engines:<br/>
Yahoo!<br/>
AltaVista<br/>
Google<br/>
<script type="text/javascript" src="js/js8.js"></script>
</body>
</html>
JavaScript:
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (i = as.length; i-- >= 0;) {
as[i].onclick = function() {
alert(i);
return false;
}
}
}
I tried to use jQuery:
$('a').click(function(event) {
var as = document.getElementsByTagName('a');
alert($(this).index());
});
but I got the index like 1,3,5 not 0,1,2
Try this (http://jsfiddle.net/bcjv6suf/):
alert($('a').index(this));
P.S. https://api.jquery.com/index/#index-selector
Update: same without jquery (you need use closure for pass argument)
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (i = as.length; i-- > 0;) {
as[i].onclick = (function(index) {
return function() {
console.log(index);
return false;
}}(i));
}
}
http://jsfiddle.net/u9f64y0c/
Here is my solution by adding a data-index attribute to the <a>.
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (var i = 0; i < as.length; i++) {
as[i].setAttribute('data-index', i);
as[i].onclick = function () {
alert(this.getAttribute('data-index'));
}
}
}
Depends what collection you are trying to find the index of for that element.
Using jQuery
Index of instance of <a> within all <a> in page:
var $links = $('a').click(function(event) {
alert($links.index(this));
});
Index within siblings group
<div id="div">
<a/>
<a/>
<a/>
</div>
$('#div a').click(function(event) {
alert($(this)index());
});
Index of element within all elements in page
$('a').click(function(event) {
alert($('*')index(this));
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test page</title>
</head>
<body>
In my life, I used the following web search engines:<br />
Yahoo!<br />
AltaVista<br />
Google<br />
<script type="text/javascript">
function registerHandlers() {
var as = document.getElementsByTagName("a");
for (var i = 0; i < as.length; i++) {
as[i].onclick = (function() {
var n = i;
return function() {
alert(n);
return false;
};
})();
}
}
registerHandlers();
</script>
</body>
</html>
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (var i = 0; i < as.length; i++) {
as[i].addEventListener('click', (function(i) {
return function(e) {
e.preventDefault();
alert(i);
}
})(i));
}
}
registerHandlers();
jQuery or exotic properties like setAttribute are not necessary. This question is about closures. Also don't forget to prevent the default behaviour, which was part of this practice question at present.
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (var i = 0; i < as.length; i++) {
const index = i; // the following anon function closes over this variable
as[i].onclick = function(event) {
event.preventDefault(); // prevent default behaviour
alert(index);
return false;
}
}
}
The simplest way to debug this is to change the var i to let i = 0. let creates its own block scope within the onclick function. So, when the value of i is returned from within the onclick function scope, the value of i is preserved and gives zero-based index value. Without this, for loop has already run and the value of i it returns is the last value, which is 3, even if you click on any link.
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (let i =0; i< as.length; i++) {
as[i].onclick = function() {
alert(i);
return false;
}
}
}
function registerHandlers() {
var as = document.getElementsByTagName("a");
for (var i = 0; i < as.length; i++) {
as[i].onclick = (function() {
var n = i;
return function() {
alert(n);
return false;
};
})();
}
}
registerHandlers();
In my life, I used the following web search engines:<br />
Yahoo!<br />
AltaVista<br />
Google<br />
I want to add onClick="" for links (in content and comments) of type bit.ly, j.mp and domain.com/go/ that don't have it already so that links look like:
link text
How do I do that?
Use plain JavaScript:
window.onload = function() {
var elements = document.getElementsByTagName('a'),
addGaqPush = function() {
_gaq.push(['_trackEvent', 'click', 'ps', 'event_house']);
};
for( var i = 0, len = elements.length; i < len; i++ ) {
elements[i].onclick = addGaqPush;
}
}
I am developing an extension for Mozilla Firefox. A main function is to get the URL that the user is visiting and process it later. I tried the following Javascript code:
window.onload = function(){
alert(document.referrer);
}
That didnt work so I tried to inject an onclick event to every link using this:
window.onload = function(){
var links = document.links;
for(var i=0;i<links.length;++i){
links[i].onclick = show_href();
}
}
function show_href(){
alert(this.href);
}
But that also doesnt work. Any other approach?
Try this:
linktextx
linktexty
linktextz
<script>
window.onload = function() {
var links = document.links;
for(var i=0;i<links.length;i++){
links[i].onclick = function(){alert(this.href)};
}
}
</script>
See: http://jsfiddle.net/uXmWj/ for working demo
In the second approach, the problem could be the for loop.
window.onload = function(){
var links = document.links,
max,
i;
for(var i=0, max = links.length; i < max; i += 1) {
(function() {
var link = links[i];
link.onclick = function() {
alert(this.href);
}
})();
}
};
var anchors = document.getElementsByTagName('a');
for(var i=0,l=anchors.length;i<l;i++)
if(anchors[i].hasAttribute('href'))
anchors[i].onclick = function(){
alert(anchors[i].getAttribute('href'));
}
I am looping through a list of links. I can correctly get the title attribute, and want it displayed onclick. When the page is loaded and when I click on a link, all of the link titles are alerted one by one. What am I doing wrong?
function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = alert(links[i].title);
}
}
What you were doing was actually running the alert function.
enclosing the whole thing in an anonymous function will only run it when it is clicked
for (var i = 0; i < links.length; i++) {
links[i].onclick = function () {
alert(this.title);
}
}
You are assigning the onclick to the return value of alert(links[i].title); which doesn't make any sense, since onclick is supposed to be a function.
What you want instead is somethig like onclick = function(){ alert('Hi'); };
But
Since you are using a variable i in that loop you need to create a local copy of it
onclick = function(){ alert(links[i].title); }; would just use the outer scope i and all your links would alert the same message.
To fix this you need to write a function that localizes i and returns a new function specific to each link's own onclick:
onclick = (function(i){ return function(e){ alert(links[i].title); }; })(i);
Final result:
function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = (function(i){ return function(e){ alert(links[i].title); }; })(i);
}
}
You can use jquery. To display title of the link on click.
$("#nav a").click(function() {
var title = $(this).attr('title');
alert(title);
});
links.forEach(function(link) {
link.onclick = function(event) {
alert(link.title);
};
}
Also note that your original solution suffered from this problem:
JavaScript closure inside loops – simple practical example
By passing in our iteration variable into a closure, we get to keep it. If we wrote the above using a for-loop, it would look like this:
// machinery needed to get the same effect as above
for (var i = 0; i < links.length; i++) {
(function(link){
link.onclick = function(event) {
alert(link.title);
}
})(links[i])
}
or
// machinery needed to get the same effect as above (version 2)
for (var i = 0; i < links.length; i++) {
(function(i){
links[i].onclick = function(event) {
alert(links[i].title);
}
})(i)
}
You need change .onclick for a eventlistener same:
function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click',function() {
alert(links[i].title);
},false);
}
}