My script contains a link a element with href attribute of "#login" as below.
Login
I want to my Javascript function detect the "href" element in the link and execute. How can I do this? My Javascript function is
window.onload = function() {
document.getElementsByTagName("a[href=#login]").onclick = function(e) {
e.preventDefault();
alert("working");
}
}
Why have I seen no querySelector love in these answers?
If you want to use that CSS selector to grab your link, nothing is stopping you:
window.onload = function() {
document.querySelector("a[href='#login']").onclick = function(e) {
e.preventDefault();
alert("working");
}
}
Login
EDIT:
I saw in another answer that you believe there may be multiple links on a page that match that selector, in which case you'll need to loop through them:
window.onload = function() {
var links = document.querySelectorAll("a[href='#login']"),
//always create anonymous functions outside of a loop :)
click = function(e) {
e.preventDefault();
alert("working");
}, i;
for (i = 0; i < links.length; i++) {
links[i].onclick = click;
}
}
Login
Login
Try this:
Login
function getValue()
{
alert("working");
e.preventDefault();
}
FIDDLE
Your getElementsByTagName is treating it like a jquery selector, which it is not designed to do.
It would be much simpler to give the tag an id and use getElementById:
window.onload = function() {
document.getElementById("loginLink").onclick = function(e) {
e.preventDefault();
alert("working");
}
}
Login
If for whatever reason you cannot change the html and you want to do it this way you would need to get all a tags then loop through each one to test the href attribute. Note you need to use a.getAttribute("href") to get "#login", rather than just a.href which oftens give you an full URL:
window.onload = function() {
var aTags = document.getElementsByTagName("a");
for(var i = 0; i < aTags.length; i++) {
var a = aTags[i];
if(a.getAttribute("href") == "#login") {
a.onclick = function(e) {
e.preventDefault();
alert("working");
}
}
}
}
Login
Test
Login Again
Related
Firstly sorry for my english, i have code that doesnt work when I execute it on
<script language="javascript" src="/thecode.js"></script>
I put thecode.js on footer
var msg=document.body.innerHTML;
for(var i=0;i<msg.length;i++){
var tx=document.body[i].innerHTML;
tx=tx.replace(/dog/ig,'animal');
tx=tx.replace(/apple/ig,'fruit');
tx=tx.replace(/\[VIdEo\]/ig,'Video');
tx=tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
document.body.innerHTML=tx;}
I think i dont make any fault, but when i execute it, its doesnt work.
thank for your attention... :)
no need to iterate body element
try this:
want to change to with that js? i have used to make it
function addTitleToSurveyUrls() {
var elements = document.getElementsByTagName('a');
for(var el in elements) {
var element = elements[el];
var href = element.getAttribute("href");
if(href.indexOf('survey_')>-1) {
element.setAttribute('title', 'Some TITLE HERE');
}
}
}
function replaceBodyElements() {
var tx=document.body.innerHTML;
tx = tx.replace(/dog/ig,'animal');
tx = tx.replace(/apple/ig,'fruit');
tx = tx.replace(/\[VIdEo\]/ig,'Video');
tx = tx.replace(/http\:\/\/example\.com/ig,'http://thelink.com');
document.body.innerHTML=tx;
}
window.onload = function(){
replaceBodyElements();
addTitleToSurveyUrls();
// ... some another operations
};
also
document.onreadystatechange = function () {
var state = document.readyState;
if(state == 'complete') {
replaceBodyElements();
addTitleToSurveyUrls();
}
}
I've used onload event because maybe document has dynamic elements and etc. so better wait while all elements get loaded and change it.
or You can replace window.onload with window.document.onload
I was successful in getting the id of all images within a div when clicking the div with the following codes below:
<script type="text/javascript">
function getimgid(){
var elems = [].slice.call( document.getElementById("card") );
elems.forEach( function( elem ){
elem.onclick = function(){
var arr = [], imgs = [].slice.call( elem.getElementsByTagName("img") );
if(imgs.length){
imgs.forEach( function( img ){
var attrID = img.id;
arr.push(attrID);
alert(arr);
});
} else {
alert("No images found.");
}
};
});
}
</script>
The codes above works perfectly, doing an alert message of the image id when clicking card div. Now what I want is to run this function without clicking the div in every 5 seconds. I have tried setInterval (getimgid, 5000), but it doesn't work. Which part of the codes above should I modify to call the function without clicking the div. Any help would be much appreciated.
JSFiddle
You should be calling it this way:
setInterval (function(){
getimgid();
},5000);
also remove binding of click event for element.
Working Fiddle
Use elem.click() to trigger click
function getimgid() {
var elems = [].slice.call(document.getElementsByClassName("card"));
elems.forEach(function (elem) {
elem.onclick = function () {
var arr = [],
imgs = [].slice.call(elem.getElementsByTagName("img"));
if (imgs.length) {
imgs.forEach(function (img) {
var attrID = img.id;
arr.push(attrID);
alert(arr);
});
} else {
alert("No images found.");
}
};
elem.click();
});
}
setInterval(getimgid, 1000);
DEMO
Problem: You are not triggering the click in setInterval. You are only re-running the event binding every 5 secs.
Solution: Set Interval on another function which triggers the click. Or remove the click binding altogether if you don't want to manually click at all.
Updated fiddle: http://jsfiddle.net/abhitalks/3Dx4w/5/
JS:
var t;
function trigger() {
var elems = [].slice.call(document.getElementsByClassName("card"));
elems.forEach(function (elem) {
elem.onclick();
});
}
t = setInterval(trigger, 5000);
From my reading here I would expect this code to work, but it doesn't. I have tried two ways to add click events to a button called "lonext". Neither work. I'm not sure why this might be?
window.onload = function() {
var goSC = function() { //go to the sucess criteria section
document.getElementsByClassName("guidance1").style.display = "none";
document.getElementsByClassName("guidance2").style.display = "";
alert("button clicked");
//first try
document.getElementById("lonext").addEventListener("click", function() {
goSC();
}, false);
//second try
document.getElementById("lonext").onclick = goSC;
}
The getElementsByClassName returns an NodeList because you could have many elements in your DOM with the same class, not a single element.
So:
var goSC = function() {
var guidance1 = document.getElementsByClassName("guidance1");
for (var i = 0; i < guidance1.length; i++) {
guidance[i].style.display = "none";
}
var guidance2 = document.getElementsByClassName("guidance2");
for (var i = 0; i < guidance2.length; i++) {
guidance[i].style.display = "";
}
alert("button clicked");
});
window.onload = function() {
document.getElementById("lonext").onclick = goSC;
};
which if you used jQuery could be simplified to:
$(function() {
$('#lonext').click(function() {
$('.guidance1').hide();
$('.guidance2').show();
});
});
I would also strongly recommend you using a javascript debugging tool such as FireBug or Chrome Developer toolbar to inspect your javascript code and see potential errors with it. The Console tab will contain valuable information about possible errors in your javascript code.
I am trying to modify the script below to click a button that looks like this on a site:
<button id="checkPrice-02070" onclick="checkPrice(02070,null); return false;" class="orangeDark">
<span>check price</span>
</button>
I am using the code below. So far, the page seems to keep reloading; nothing else happens.
Any advice to someone new?
(function () {
window.addEventListener("load", function (e) {
clickConfirmButton()
}, false);
})();
function clickConfirmButton() {
var buttons = document.getElementsByTagName('button');
var clicked = false;
for (var index = 0; (index < buttons.length); index++) {
if (buttons[index].value == "check price") {
buttons[index].click();
clicked = true;
break;
}
}
if (!clicked) {
setTimeout("window.location.reload()", 300 * 1000);
}
}
A <button>s value is not the visible text. You'd want to search textContent.
However:
If that sample HTML is correct, you'd be better off searching for ids that start with checkPrice. See the code below.
Are you sure you want to reload if the button is not found? If it is added by AJAX this is not the best approach. See this answer.
Don't use setTimeout with a string (to evaluate) argument like that. See the code below.
You do not need to wrap the code in an anonymous function.
Anyway, this should work, given the sample HTML:
window.addEventListener ("load", clickConfirmButton, false);
function clickConfirmButton (zEvent) {
var button = document.querySelector ("button[id^='checkPrice']");
if (button) {
button.click ();
}
else {
setTimeout (function () { location.reload(); }, 300 * 1000);
}
}
To check the button text anyway, use:
function clickConfirmButton (zEvent) {
var buttons = document.querySelectorAll ("button[id^='checkPrice']");
var clicked = false;
for (var index = 0, numBtn = buttons.length; index < numBtn; ++index) {
if (/check price/i.test (buttons[index].textContent) ) {
buttons[index].click();
clicked = true;
break;
}
}
if (!clicked) {
setTimeout (function () { location.reload(); }, 300 * 1000);
}
}
I'm trying to build a Javascript listener for a small page that uses AJAX to load content based on the anchor in the URL. Looking online, I found and modified a script that uses setInterval() to do this and so far it works fine. However, I have other jQuery elements in the $(document).ready() for special effects for the menus and content. If I use setInterval() no other jQuery effects work. I finagled a way to get it work by including the jQuery effects in the loop for setInterval() like so:
$(document).ready(function() {
var pageScripts = function() {
pageEffects();
pageURL();
}
window.setInterval(pageScripts, 500);
});
var currentAnchor = null;
function pageEffects() {
// Popup Menus
$(".bannerMenu").hover(function() {
$(this).find("ul.bannerSubmenu").slideDown(300).show;
}, function() {
$(this).find("ul.bannerSubmenu").slideUp(400);
});
$(".panel").hover(function() {
$(this).find(".panelContent").fadeIn(200);
}, function() {
$(this).find(".panelContent").fadeOut(300);
});
// REL Links Control
$("a[rel='_blank']").click(function() {
this.target = "_blank";
});
$("a[rel='share']").click(function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
}
function pageURL() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
$.get("loader.php", query, function(data) {
$("#load").fadeIn("fast");
$("#content").fadeOut(100).html(data).fadeIn(500);
$("#load").fadeOut("fast");
});
}
}
This works fine for a while but after a few minutes of the page being loaded, it drags to a near stop in IE and Firefox. I checked the FF Error Console and it comes back with an error "Too many Recursions." Chrome seems to not care and the page continues to run more or less normally despite the amount of time it's been open.
It would seem to me that the pageEffects() call is causing the issue with the recursion, however, any attempts to move it out of the loop breaks them and they cease to work as soon as setInterval makes it first loop.
Any help on this would be greatly appreciated!
I am guessing that the pageEffects need added to the pageURL content.
At the very least this should be more efficient and prevent duplicate handlers
$(document).ready(function() {
pageEffects($('body'));
(function(){
pageURL();
window.setTimeout(arguments.callee, 500);
})();
});
var currentAnchor = null;
function pageEffects(parent) {
// Popup Menus
parent.find(".bannerMenu").each(function() {
$(this).unbind('mouseenter mouseleave');
var proxy = {
subMenu: $(this).find("ul.bannerSubmenu"),
handlerIn: function() {
this.subMenu.slideDown(300).show();
},
handlerOut: function() {
this.subMenu.slideUp(400).hide();
}
};
$(this).hover(proxy.handlerIn, proxy.handlerOut);
});
parent.find(".panel").each(function() {
$(this).unbind('mouseenter mouseleave');
var proxy = {
content: panel.find(".panelContent"),
handlerIn: function() {
this.content.fadeIn(200).show();
},
handlerOut: function() {
this.content.slideUp(400).hide();
}
};
$(this).hover(proxy.handlerIn, proxy.handlerOut);
});
// REL Links Control
parent.find("a[rel='_blank']").each(function() {
$(this).target = "_blank";
});
parent.find("a[rel='share']").click(function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
}
function pageURL() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
var content = $("#content");
$.get("loader.php", query, function(data) {
$("#load").fadeIn("fast");
content.fadeOut(100).html(data).fadeIn(500);
$("#load").fadeOut("fast");
});
pageEffects(content);
}
}
Thanks for the suggestions. I tried a few of them and they still did not lead to the desirable effects. After some cautious testing, I found out what was happening. With jQuery (and presumably Javascript as a whole), whenever an AJAX callback is made, the elements brought in through the callback are not binded to what was originally binded in the document, they must be rebinded. You can either do this by recalling all the jQuery events on a successful callback or by using the .live() event in jQuery's library. I opted for .live() and it works like a charm now and no more recursive errors :D.
$(document).ready(function() {
// Popup Menus
$(".bannerMenu").live("hover", function(event) {
if (event.type == "mouseover") {
$(this).find("ul.bannerSubmenu").slideDown(300);
} else {
$(this).find("ul.bannerSubmenu").slideUp(400);
}
});
// Rollover Content
$(".panel").live("hover", function(event) {
if (event.type == "mouseover") {
$(this).find(".panelContent").fadeIn(200);
} else {
$(this).find(".panelContent").fadeOut(300);
}
});
// HREF Events
$("a[rel='_blank']").live("click", function(event) {
var target = $(this).attr("href");
window.open(target, "_blank");
event.preventDefault();
});
$("a[rel='share']").live("click", function(event) {
var share_url = $(this).attr("href");
window.open(share_url, "Share", "width=768, height=450");
event.preventDefault();
});
setInterval("checkAnchor()", 500);
});
var currentAnchor = null;
function checkAnchor() {
if (currentAnchor != document.location.hash) {
currentAnchor = document.location.hash;
if (!currentAnchor) {
query = "section=home";
} else {
var splits = currentAnchor.substring(1).split("&");
var section = splits[0];
delete splits[0];
var params = splits.join("&");
var query = "section=" + section + params;
}
$.get("loader.php", query, function(data) {
$("#load").fadeIn(200);
$("#content").fadeOut(200).html(data).fadeIn(200);
$("#load").fadeOut(200);
});
}
}
Anywho, the page works as intended even in IE (which I rarely check for compatibility). Hopefully, some other newb will learn from my mistakes :p.