JavaScript to change links on page? - javascript

I'm pretty new to JavaScript and am wondering how on a page with links to images, i.e. http://www.example.com/image.jpg I can get them to be changed automatically by JavaScript to be embedded, ie with <img> tag
Hope that makes sense!
Thanks

We're particularly fond of the jQuery framework here, as it makes this sort of task very easy. With jQuery on your page, you can easily do this:
$(document).ready(function() {
$('a[href$=.jpg]').each(function() {
var imageSrc = $(this).attr('href');
var img = $('<img />').attr('src', imageSrc);
$(this).replaceWith(img);
});
});
This will work specifically for <a> tags whose href attributes end with .jpg You can expand it to other file extensions, of course, but to dynamically determine whether a link leads to an image if the URL is not obvious would be a far greater challenge.

Do you mean convert all image url's to hyperlinks "pointing" to the images?
var x = document.getElementById('body');
x.innerHTML = x.innerHTML.replace(/(http:\/\/[^ ]+)/g,'$1/');
I haven't tested this, but it should work. No third-party frameworks are needed.
From here

Related

How to recursively get all the links present in a website using Javascript?

I'm looking for the way to recursively find all the links present on any given website. I know how to do this in java but I don't know how it can be done using javascript.
Consider this image represents a website directory and if we provide 'www.abc.com' ,then it should return following output.
www.abc.com\images
www.abc.com\files
www.abc.com\images\a.jpg
www.abc.com\images\b.jpg
www.abc.com\files\aa.txt
www.abc.com\files\bb.txt
Since the question is tagged jQuery, I'll use that. Simply target the a tags.
var linksList = [];
function addLink(url){
if(url!= "" && linksList.indexOf(url) == -1){
links.list.push(url);
scrapePage(url);
}
}
function scrapePage(url){
$.get(url,function(html){
var $iframe = $('body').append('iframe');
$iframe.contents().find("body").html(html);
$iframe.contents().find("body a").each(function(index,link){
addLink(link.href);
});
$iframe.remove();
});
}
$("body a").each(function(index,link){
addLink(link.href);
});
Pretty simple, a function to add links in our list, another to follow the links we add. I decided to put the content of the scraped page inside an iframe to keep everything restrained...
You'll want to add your logic to make sure it takes only links that are from the domain. You might need to play with the URL as it will not be absolute (but considered it is in my code). And so on.
In js getElementsByTagName("a")
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
In jquery $("a")
I think you cannot get all the links of a particular website. But you can get all the link of particular page like below :-
var allLinks = document.getElementsByTagName("a");
Hope it helps. It would be great if you elaborate your issue more.

Change all external links using jQuery

I want to change all external links on my blog (blogspot here, that's why I'm looking for jQuery code) without changing the posting of my blog because I need a lot of work if I do that.
For example, my website is example.com.
I want to change all external links to
http://example.com/p/go.html?url=http://externallink.com
without need for any changes on my blog post. I don't have any idea to start with.
SOLVED: https://gist.github.com/2342509 Thanks everyone :D I just need to change it a bit.
In jQuery you can try:
// DOM ready
$(function(){
$('a[target="_blank"]').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');
});
Ofcourse this will only work if you have set the target="_blank" property/attribute in HTML and if you want all links to open the same url. This idea derives from the fact you want to have external links open automatically in a different tab/window.
If this is not the required functionality, you can use a custom data- attribute in a similar way. Only difference is you will need to loop each link, and get the data from it.
// DOM ready
$(function(){
$('a[data-href]').each(function(){
var anc = $(this),
href = anc.prop('href'),
dataHref = anc.data('href');
anc.prop('href', href + '?url=' + dataHref);
});
});
HTML example:
external link
And now you will probably need to add more information if that is still not what you want.
Going off of #Tim Vermaelan's answer, you could try this, which will check for every link that doesn't start with your website's URL without relying on it being target="_blank":
$('a:not([href^="http://yoursite.com"])').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');

Using jQuery to change href after .load() call

I'm pretty new to web design but since some months I'm trying to learn some basic knowledge to work with html, css, JavaScript an so on. I've followed and tried to understand all the basic tutorials found on w3cschool and other introducting sites, with no particular problem with structure in html nor styling with css, but now I'm facing JavaScript and here's the question, but let me explain first what I'm trying to achieve.
On the site I'm triyng to conceive I've created a side panel which must contain some titles and short descriptions of articles taken from another site, with another domain.
Due to my very poor experience and to the informations found on the web, I thought that jQuery could help me in this task, in particular with its load() method. So, after saving a copy in .txt format of the source page where the titles are, I wrote a very simple code in my document's head:
$(document).ready(function() {
$("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)");
$("#myDiv2 p").load("copyOfSite.txt .list a:eq(1)");
$("#myDiv3 p").load("copyOfSite.txt .list a:eq(2)");
});
This was working fine, except for the fact that the titles I am calling are relative links to articles with another domain, so they don't work in my site.
I've tried to specify a function in the second part of the load method but I couldn't find a way to prepend the domain of the other site to the href attribute I've loaded. I've only achieved to specify an url or to remove the loaded url with something like
$(document).ready(function() {
$("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)",function(data){
$(this).find("[href]").attr('href','http://www.articlesdomain.com')}
)};
or
$(document).ready(function() {
$("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)",function(data){
$(this).find("[href]").removeAttr('href')}
)};
but in both cases I cannot manage to call the href attribute of my loaded title and append to the articles domain. So I'm wondering if there's a way to achieve it or if my approach to the task is completely wrong.
Thanks in advance
You need to prepend the protocol and hostname to the already existing relative href's, right now you're replacing the entire href with the new url.
Use a function to get each href, and just prepend the hostname to what's already there :
$("#myDiv1 p").load("copyOfSite.txt .list a:eq(0)",function(data){
$(this).find("[href]").attr('href', function(_,href) {
return 'http://www.articlesdomain.com' + href;
});
)};
note that the relative hrefs should start with /, otherwise you'll have to add that to the end of the prepended url as well
$(function () {
$('a.something').click(function (e) {
e.preventDefault();
});

How to pull images from the DOM in javascript?

If you have looked at Pinterest you will know they have a bookmarklet that the user can press and it loads up more javascript which gathers certain images from the DOM and lets them pin them at the site. I found the gathering images interesting and would like to be able to do that. Where would I be able to look to learn how to gather images from the DOM so that I could let the user do stuff with them? I have done google searches but most are about scraping with php and that doesn't really work if the user is on a page that requires login, for instance.
Am not very sure what you are asking but here is how you get an image using javascript:
var images = document.getElementsByTagName("img");
This will return a nodeList which you can loop through to work on a single image at a time
for (var i=0,l=images.length;i<l;i++){
// your code here
console.log(images[i].src);
}
it is actually quite simple using jquery http://jquery.com/
you can do a simple selector like $('img') .. which will give you a collection of all the images on a page ... from that you can get the source of any of them using $('img').first().attr('src') <=== this will return the source of the first image on the page
hope this helps
Create a bookmarklet. To get all the images on the page do something like this:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var imageSrc = images[i].src;
// Do something with the image
// ie, add it to the DOM and let them select one.
// It also might be worth looking at the offsetWidth property to only grab larger images
}
Here's the source to the Pinterest bookmarklet for reference

How can I determine img width/height of dynamically loaded images in IE?

My markup is a simple div element with id 'load'. Using jQuery I then load a list of image elements into this div:
$('#load').load('images.html', { }, function() {
$(this).onImagesLoad({
selectorCallback: function() {
....do something....
}
});
});
where images.html is a list like this:
<img src='1.jpg' caption='img 1'>
<img src='2.jpg' caption='img 2'>
...
To ensure that all images are loaded completely, I use the onImagesLoad plugin. This, so far, works just fine on all browsers.
However, on IE8 (and I assume other versions of IE also) when I then iterate over the img elements, I am unable to determine the width/height of the images loaded. The image.context.naturalWidth and naturalHeight attributes don't seem to work.
How do I get a hold of the images' dimension?
Thanks heaps :)
Update
#Simon: That didn't work on IE, and broke the other browsers as well.
#Jenechka: If "imageDomElement" is just another name for the "image" variable in my example above, then it doesn't work. Or what do you mean by that DomElement?
If you haven't resized the image, you could use:
image.width()
and
image.height()
It's been a while but I finally found some time to tinker with this again. The above problems are still there, but here is what I think is going on.
When I load the initial images then yes, the file is loaded and image objects are generated. But it seems that the attributes are not correct yet, and they won't be until the image is actually added to the DOM of the site and rendered. A div/image on hide() on IE has no dimension information whatsoever, on Safari there is some information available. For example, without adding the following div anywhere
var test = $("<div><img src='test.jpg'></div>")
the image contained there has the following information:
width() = 0,
attr("width") = 600,
css("width") = "", and
img[0].clientWidth = 0.
That's on Safari; on IE it's the same except attr("width") = 0 and css("width") = "auto". Now I can't use this, and that's what broke my script and why I posted my initial question. However, the moment I append this div and have it rendered, all the correct values show up in the image object.
I'm writing a little gallery thinghie, which shows whatever images I have in that second .html file that I load; that gallery, however, computes and places the thumbnails, and prepares the images it shows in full resolution. To make this look ok, I basically wanted to create the entire thing hidden, and then fade it in. Alas, it seems that this whole idea won't pan out. A friend suggested to load everything into a tiny iframe off to the left where it's not visible, and work with that. Perhaps that's the way to go.
Another thing I noticed, and that seems to be very closely related to the aforementioned load issue is clone(). It seems that if an image is rendered, a
var newimg = img.clone()
generates the same "empty" image object that I have to deal above. Even when the original image is visible and contains all the right attributes, its clone does not.
Right now I don't see any other way than to rethink and rewrite parts of my gallery.
This is quite similar to the other answers, but I have tested it in IE7, so it might be closer to what you want:
$(document).onImagesLoad({
selectorCallback: function() {
$('img').each(function(){
alert($(this).width()+', '+$(this).height());
});
}
});
See here, this may not be exactly how you were using it, but I'm not familiar with this onImagesLoad thing.
imageDomElement.width
imageDomElement.height
or try
imageDomElement.clientWidth
imageDomElement.clientHeight
If you play with jquery, then image.attr(width) should do the trick
But why not using the document.ready instead, could give you less headeache. .
Use the following code instead
$(document).onImagesLoad({
selectorCallback: function() {
$('img').each(function(){
alert($(this)[0].clientWidth +', '+$(this)[0].clientHeight);
});
}
});
What about?
$("#load img").each(function() {
var img = new Image();
img.src = this.src;
alert(img.height + " x " + img.width);
});

Categories

Resources