The link's code is as follows:
<td class="buttonColumn">
Leave to Google
</td>
<td class="buttonColumn">
Leave to Yahoo
</td>
There are multiple buttons on the page with the exact same format that need to be changed as well. I was thinking something like this:
var fix = document.getElementsByClassName('actionButtonNew');
for (var i=0; i<fix.length; i++) {
I am not sure how to finish the code. I tried this:
var fix = document.getElementsByClassName('actionButtonNew');
for(var i = 0; i < fix.length; i++) {
try {
var l = fix[i];
var h = fix[i].parentNode.getElementsByClassName('actionButtonNew')[0].href.replace("javascript:confirmDialog('Are you sure you want to go?',", "");
l.href = h;
} catch(e) {}
}
I know it is very messy and bad. It does change the link to: 'http://google.com');
So I think I may be on the right track. Please help me. Thanks in advance!
Here's an idea: rather than deal with messy regular expressions that are bound to break on some edge case, replace confirmDialog with a function that redirects without confirming:
window.noConfirm = function(m, url) {
document.location.href = url;
}
var fix = document.getElementsByClassName('actionButtonNew');
for (var i = 0; i < fix.length; i++) {
fix[i].href = fix[i].href.replace('confirmDialog', 'noConfirm');
}
http://jsfiddle.net/AV4tB/
And another funny idea: change it call a function that immediately fixes the link, then trigger a click:
window.fixMe = function(m, url) {
this.href = url;
}
var linksToFix = document.getElementsByClassName('actionButtonNew');
for (var i = 0; i < linksToFix.length; i++) {
window.a = linksToFix[i];
linksToFix[i].href = linksToFix[i].href.replace('confirmDialog(', 'fixMe.call(a, ');
linksToFix[i].click();
}
http://jsfiddle.net/AV4tB/1/
Try this:
var fix = document.getElementsByClassName('actionButtonNew');
for (var i = 0; i < fix.length; i++) {
fix[i].href = fix[i].href.replace(/javascript:confirmDialog\(\'Are you sure you want go\?\'\, \'(http\:\/\/.*\.(.){2,3})'\);/gi,'$1');
}
Which uses regex to replace the confirm JS with just the links.
E.g. "javascript:confirmDialog('Are you sure you want go?', 'http://yahoo.com');" becomes "http://yahoo.com"
Pretty annoying to say to users "do you really want to do that?" every time they click on a link. After all, the back button will usually bring them straight back, or the escape key will cancel navigation if they're quick.
Since A elements may not all be links (some are targets), you can get all the links in a page using the document.links collection, then iterate over that:
// Function to call
function navPrompt() {
var text = this.textContent || this.innerText
return confirm('Are you sure you want to go to ' + text + '?');
}
// Attach to all listeners
window.onload = function() {
var links = document.links;
var i = links.length;
while (i--) {
links[i].onclick = navPrompt;
}
}
On the otherhand, if you want to remove the comfirm box and change:
href="javascript:confirmDialog('Are you sure you want go?', 'http://google.com');"
to:
href="http://google.com"
you can do:
window.onload = function() {
var link, links = document.links;
var i = links.length;
while (i--) {
link = links[i];
link.href = link.href.replace(/.*(http[^\'\"]+).+/i,'$1');
}
}
Which will strip out the URL and assign it to the href property.
Related
I am interested in when choosing an option from a drop-down list the value of the selected option that stá visualiando in a < div > that value is captured in a javascript variable. The list referred to originated in an AJAX routine that queries a database. On page php , where there is a div shown above . I need your help to take this value from the list.
Assuming that you meant for your question read the way RightClick explained it in the comments, you need something like this:
window.onload = function() {
var ids = $('.dropdown').map(function(){
return this.id;
}).get();//Get array of ids
var options = document.getElementsByClassName('dropdown');
for(var i = 0; i < options.length; i++) {
var anchor = options[i];
anchor.onclick = function() {
var h = new XMLHttpRequest();
h.open("GET", "/myDB?q="+ids[i], true);//This should be synchronous
h.send();
document.getElementById("responseDiv").innerHTML = h.responseText;
}
}
}
`
I am trying to place background images for divs with JS and change those images on mouse over and on click. I am trying to do it like this:
window.onload; {
var replies = document.getElementsByClassName("reply-wrapper");
var retweets = document.getElementsByClassName("retweet-wrapper");
var favs = document.getElementsByClassName("fav-wrapper");
for (var i = 0; i < replies.length; i++) {
replies[i].style.backgroundImage = "url(images/reply.png);";
}
for (var i = 0; i < retweets.length; i++) {
retweets[i].style.backgroundImage = "url(images/retweet.png);";
}
for (var i = 0; i < favs.length; i++) {
favs[i].style.backgroundImage = "url(images/favorite.png);";
}
}
But for some reason it won't work. Aprropriate divs have right classes and adding them to collection works fine, but placing images itself doesn't work. What am I doing wrong?
P.S. Wanna write it in pure JS, no jQuery.
P.P.S For some reason placing image with innerHTML works fine. Why?
It looks like you've made a slight mistake when assigning your code to the window.onload event.
Your code needs to be in a function assigned to the onload event.
window.onload = function () { /* Your Code */ };
instead of:
window.onload; { /* Your Code /* }
There are two issues:
Like Jamie Dixon mentioned it needs to be window.onload = function(){}
favs[i].style.backgroundImage = "url(images/favorite.png);"; should be favs[i].style.backgroundImage = "url(images/favorite.png)"; The extra ; will cause your link not to work. So remove the extra semi-colon from the rest of your links.
Update with explanation:
#room1 {
background-image: url('image/example.png');
}
In the example above you'll notice the semi-colon. Like in any programming language this is to say that this is the end of the command. Sometimes semi-colon's are optional ( like in certain cases found in js ).
JS isn't CSS. Even if you apply a style to your html element, you are using JS and not CSS. This is why you don't need the ; inside the quotes.
The event handler window.onload needs to be assigned a function to invoke. So, you just need to add the keyword 'function' before the block of code and then assign that to window.onload. Additionally, if you want to play nice with other code on the page you could grab a reference to any existing onload handler and then invoke in your onload function.
var oldOnLoad = window.onload;
window.onload = function() {
if (typeof oldOnLoad === 'function') {
oldOnLoad();
}
var replies = document.getElementsByClassName("reply-wrapper");
var retweets = document.getElementsByClassName("retweet-wrapper");
var favs = document.getElementsByClassName("fav-wrapper");
for (var i = 0; i < replies.length; i++) {
replies[i].style.backgroundImage = "url(images/reply.png)";
}
for (var i = 0; i < retweets.length; i++) {
retweets[i].style.backgroundImage = "url(images/retweet.png)";
}
for (var i = 0; i < favs.length; i++) {
favs[i].style.backgroundImage = "url(images/favorite.png)";
}
};
Note: it might be worth mentioning that loading the background images in the onload event handler could cause your page to appear to load slow because it will wait for all other content on the page to finish loading. You might want to do something like instead:
<div id="reply-wrapper" style="display: block; width: 250px; height: 250px;"></div>
<script>
(function() {
document.getElementById('reply-wrapper').style.backgroundImage = "url(//dummyimage.com/250x250/000/fff)";
})();
</script>
I don't see a function name for the code.
Is it incomplete?
this might be the error.
window.onLoad;
Try this:
function fn_load(){
// Your statements
}
and in the body do this:
i should be:
window.onload = function() {
var replies = document.getElementsByClassName("reply-wrapper");
var retweets = document.getElementsByClassName("retweet-wrapper");
var favs = document.getElementsByClassName("fav-wrapper");
for (var i = 0; i < replies.length; i++) {
replies[i].style.backgroundImage = "url(images/reply.png);";
}
for (var i = 0; i < retweets.length; i++) {
retweets[i].style.backgroundImage = "url(images/retweet.png);";
}
for (var i = 0; i < favs.length; i++) {
favs[i].style.backgroundImage = "url(images/favorite.png);";
}
}
you DOM is calling even before window got load.
Here's my issue. I made a function that resolves links in javascript, but the use-case I'm stuck with is that there may already be HTML in posts with links.
Users can not post true HTML, but moderators and administrators can, meaning I need to handle both cases.
Here's an example of your typical user post HTML:
<div class="teaser">
This is just your normal post http://google.com some other stuff
</div>
And administrator/moderator:
<div class="teaser">
<b>
THIS LINK
</b>
<br><br>
Supplemental reading: Link again
</div>
Normally, I'd use something like
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1' target='_blank'>$1</a>");
}
c.not('a').each(function() {
var html = $(this).html();
$(this).html(replaceURLWithHTMLLinks(html));
});
But this causes links to be parsed which exist inside of the href property. I need to be able to create links only when they are outside of tags, and it needs to be through all children as you'll notice that is the first child in a mod/admin post (if they so choose).
Mods and admins can put basically any HTML they desire in their posts, so the tag could be anywhere in the post hierarchy which is not at all consistent.
I could just not parse links on admin or mod posts, but sometimes some mods and admins use the proper HTML tags, and sometimes they don't, which is why I'd like to know the proper way of doing this.
Try this:
var exp = /^(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
$('.teaser').each(function() {
var i, words;
$this = $(this);
words = $this.html().split(' ');
for (i = 0; i < words.length; i++) {
if (exp.test(words[i])) {
words[i] = words[i].replace(exp, "<a href='$1' target='_blank'>$1</a>");
}
}
$this.html(words.join(' '));
});
Demo Link
I found the answer here it seems.
filterTeaserLinkContent: function(data) {
var exp = /\b((https?|ftps?|about|bitcoin|git|irc[s6]?):(\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/|magnet:\?(dn|x[lts]|as|kt|mt|tr)=)([^\s()<>]+|\([^\s()<>]+\))+(\([^\s()<>]+\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])/g;
var nodes = data[0].childNodes;
for(var i = 0; i < nodes.length; i++) {
var n = nodes[i];
if(n.nodeType == n.TEXT_NODE || n.nodeName == 'BR') {
var g = n.textContent.match(exp);
while(g) {
var idx=n.textContent.indexOf(g[0]);
var pre=n.textContent.substring(0,idx);
var a=document.createElement("a");
if (!/^[a-z][\w-]+:/.test(g[0])) {
a.href = "http://" + g[0];
} else {
a.href = g[0];
}
a.innerText = g[0];
n.textContent = n.textContent.substring(idx+g[0].length);
n.parentElement.insertBefore(a,n);
g=n.textContent.match(exp);
}
} else {
Board.filterTeaserLinkContent($(n));
}
}
},
filterTeaserContent: function(data) {
// Jam into <div> so we can play with it
var c = $('<div>' + data + '</div>');
// Remove <wbr> tag which breaks links
c.find('wbr').each(function() {
$(this).remove();
});
// Re-parse the HTML after removing <wbr> or else the text nodes won't be joined
c = $('<div>' + c.html() + '</div>');
// I actually forget what this does, but fuck it. Shit.
c.not("div, s, span, a").each(function() {
var content = $(this).contents();
$(this).replaceWith(content);
});
Board.filterTeaserLinkContent(c);
// Remove images in post preview because they don't need to be here...
c.find('img').each(function() {
$(this).remove();
});
// Simplify line breaks
return c.html().replace(/<br ?\/?><br ?\/?>/g, "<br>");
},
This is for use in the 4chan API in case anyone was curious.
I'm on a website that is not mine, and an HTTP GET request is called onmouseover on a link. The result is a <table> which is removed onmouseout.
Is it possible for me to edit the contents of the <table> before it is called?
I have tried adding a second EventListener to the link but it only gets called before the <table> is created:
var matchupTable = document.getElementById('chessvs'),
matchupProfileLink = matchupTable.getElementsByTagName('a');
function getHoverProfile() {
var i, currentLink;
for (i = 0; i < matchupProfileLink.length; i += 1) {
currentLink = matchupProfileLink[i];
if (currentLink.innerHTML !== gk_uid && currentLink.title !== 'premium subscriber') {
currentLink.addEventListener('mouseover',
function hideHoverRank() {
var hoverProfile = document.getElementsByTagName('table'),
currentTable, i;
for (i = 0; i < hoverProfile.length; i += 1) {
currentTable = hoverProfile[i];
console.log(currentTable);
}
}, false);
}
}
}
getHoverProfile();
The only table in your example is in document. You can do whatever you want with it. You can also try to unbind the original get-success handler on all anchors in chessvs.
How can I go through all external links in a div with javascript, adding (or appending) a class and alt-text?
I guess I need to fetch all objects inside the div element, then check if each object is a , and check if the href attributen starts with http(s):// (should then be an external link), then add content to the alt and class attribute (if they don't exist create them, if they do exists; append the wanted values).
But, how do I do this in code?
This one is tested:
<style type="text/css">
.AddedClass
{
background-color: #88FF99;
}
</style>
<script type="text/javascript">
window.onload = function ()
{
var re = /^(https?:\/\/[^\/]+).*$/;
var currentHref = window.location.href.replace(re, '$1');
var reLocal = new RegExp('^' + currentHref.replace(/\./, '\\.'));
var linksDiv = document.getElementById("Links");
if (linksDiv == null) return;
var links = linksDiv.getElementsByTagName("a");
for (var i = 0; i < links.length; i++)
{
var href = links[i].href;
if (href == '' || reLocal.test(href) || !/^http/.test(href))
continue;
if (links[i].className != undefined)
{
links[i].className += ' AddedClass';
}
else
{
links[i].className = 'AddedClass';
}
if (links[i].title != undefined && links[i].title != '')
{
links[i].title += ' (outside link)';
}
else
{
links[i].title = 'Outside link';
}
}
}
</script>
<div id="Links">
<a name="_Links"></a>
FOO
FILE
SomeWhere
SomeWhere 2
SomeWhere 3
ElseWhere 1
ElseWhere 2
ElseWhere 3
BAR
Show/Hide
</div>
If you are on an account on a shared server, like http://big-server.com/~UserName/, you might want to hard-code the URL to go beyond the top level. On the other hand, you might want to alter the RE if you want http://foo.my-server.com and http://bar.my-server.com marked as local.
[UPDATE] Improved robustness after good remarks...
I don't highlight FTP or other protocols, they probably deserve a distinct routine.
I think something like this could be a starting point:
var links = document.getElementsByTagName("a"); //use div object here instead of document
for (var i=0; i<links.length; i++)
{
if (links[i].href.substring(0, 5) == 'https')
{
links[i].setAttribute('title', 'abc');
links[i].setAttribute('class', 'abc');
links[i].setAttribute('className', 'abc');
}
}
you could also loop through all the A elements in the document, and check the parent to see if the div is the one you are looking for
This can be accomplished pretty easily with Jquery. You would add this to the onload:
$("div a[href^='http']").each(function() {
$(this).attr("alt",altText);
var oldClassAttributeValue = $(this).attr("class");
if(!oldClassAttributeValue) {
$(this).attr("class",newClassAttributeValue);
}
});
You could modify this to add text. Class can also be modified using the css function.
My (non-framework) approach would be something along the lines of:
window.onload = function(){
targetDiv = document.getElementById("divName");
linksArray = targetDiv.getElementsByTagName("a");
for(i=0;i=linksArray.length;i++){
thisLink = linksArray[i].href;
if(thisLink.substring(4,0) = "http"){
linksArray[i].className += "yourcontent"; //you said append so +=
linksArray[i].alt += "yourcontent";
}
}
}
This is not tested but I would start like this and debug it from here.