How to change a website image with javascript? [duplicate] - javascript

I'm working with my first Greasemonkey script.
And its for a website that have a logo, i want to change the image to a image i have created, and i wonder how i do this?
like use JavaScript to edit the current html document and replace the image.
Thanks for any help!
Edit: The image is inside a <img> tag, the image i want to change/replace is in this code:
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo" width="170" height="36">
Here is the javascript code i tryed and didnt work:
var myImage = document.querySelector('.fb_logo img');
myImage.src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";

var logos = document.getElementsByClassName("fb_logo");
for( var i = 0; i < logos.length; i++ )
{
// true for all img tags with the fb_logo class name
if( logos[ i ].tagName == "IMG" )
{
logos[ i ].src = "http://www.computerweekly.com/blogs/it-downtime-blog/lolcat-tan.jpg"
}
}

Knowing that you can use browser-specific javascript is a plus.
Use querySelectorAll.
var img = document.querySelectorAll('.yourClass')[0];
Note: you're possibly selecting more than one element, so it's returning a nodelist rather than a single node, remember to select the first item in the list.
Better yet, use querySelector
var img = document.querySelector('.yourClass');

Okay, here's a complete Greasemonkey script that swaps the logo image at Facebook under real-world conditions (meaning that the image may be in different places and you have to deal with the container and background images, etc.).
Note that this script looks for the image in two types of locations, and deals with the surrounding HTML, and CSS, if necessary.
Also note that it uses jQuery -- which is a godsend for writing GM scripts.
Finally: note that I avoid Facebook, and only know of the one logo location (plus the one that the OP reports. If there are new/different locations, deal with them in a similar manner.
// ==UserScript==
// #name _Facebook Logo Swap
// #include http://www.facebook.com/*
// #include https://www.facebook.com/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
/*--- Found FB logo at:
"h1#pageLogo a" as a backgound image.
It's reportedly also at: "img.fb_logo.img"
*/
var desiredImage = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
//--- Straight image swap:
$('img.fb_logo').attr ('src', desiredImage);
/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
Since this image is transparent, clear the old BG image.
Also constrain the new img to its container.
*/
$('#pageLogo a').css ('background-image', 'none')
.append ('<img>').find ('img') .attr ('src', desiredImage)
.css ( {width: '100%', height: '100%'} );

find the image tag and replace the src attribute.
var myImage = document.getElementById(idOfImageYouNeedToChange);
myImage.src = "your_image";
Pretty straightforward.

You can do this very simply with jQuery
$('.fb_logo').attr('src','newimage.jpg');

you have to get the reference to your img element first, better use id instead of a class, since getElementsByClassName is not supported in IE until ie9:
with raw javascript (there are many ways of doing this. this is just the one):
var theImg = document.getElementById('imageId');
theImg.src = 'someNewPath'
with something like jQuery(js library) - you can easily select by class or by id or by tag etc:
$('.yourPicClass').attr('src', 'someNewPath')

How about using the DOM to find that specific attribute and change it to whatever?
<html>
<body>
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var yerImg = document.getElementsByTagName("img");
yerImg[0].setAttribute("src", "http://goo.gl/JP8bQ");
</script>
</html>

querySelector:
return the first matching Element node within the node’s subtrees. If there is no such node, the method must return null.
querySelectorAll:
return a NodeList containing all of the matching Element nodes within the node’s subtrees, in document order. If there are no such nodes, the method must return an empty NodeList.
The Use :
var element = baseElement.querySelector(selectors);
var elementList = baseElement.querySelectorAll(selectors);
Sample :
<html>
<body>
<img class="fb_logo" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var myImageList = document.querySelectorAll('.fb_logo');
myImageList[0].src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
</script>
</html>

Related

How to get a the url of an image from id in Javascript

I know it's such a beginner thing. So I have this image in a div with the id thumb.
<img id="thumb" src="https://url-to-a-image">
And this Javascript that it's a magnify script:
<script type="text/javascript">
var myImgSrc = document.getElementById("thumb").getElementsByTagName("img")
[0].src;
var evt = new Event(),
m = new Magnifier(evt);
m.attach({
thumb: '#thumb',
large: 'myImgSrc',
largeWrapper: 'preview'
});
</script>
As you can see I'm trying to get the image using myImgSrc and then I'm trying to use in the large: 'myImgSrc'. When I put the a fixed url in large: fixed-url-to-the-image, it works fine.
The element with #thumb id is the tag img it self, the current selector will not return the src value, so it should be simply:
var myImgSrc = document.getElementById("thumb").src;
You can get image src like this,
var thumb = document.getElementById("thumb").src;
You don't need to use getElementsByTagName.
let img = document.querySelector('#thumb');
console.log(img.src);
If you use img.src, you'll see the source of your img tag.
getElementsByTagName is superfluous - you already have the exact element you want - you selected it by its ID. You'd only need getElementsByTagName if you wanted to get one or more elements by their tag and work on them all, rather than identifying one precisely.
So actually the solution is very simple - just get the src attribute of the ID-selected element directly. Working demo:
var myImgSrc = document.getElementById("thumb").src;
console.log(myImgSrc);
<img id="thumb" src="https://url-to-a-image">

Cannot append image with jquery

I currently have a code working where i can add a class based on the url of a page using jquery. However I would like add an image to a div instead of just adding a class. I'm not as proficient in java-script as I could be but I think there is probably a pretty simple solution. The code that doesn't work is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var img = document.createElement("img");
img.src = '~/Content/Images/Template 5A Filmstrip.jpg" />';
}
the code that works right now that I dont want to use is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var $body = $('body');
$body.addClass('campaign');
}
How can apply what I do know that works to what I am trying to get to work?
If for some reason you don't want to use jQuery for this part, you just need to append the element to the body of the html document (or wherever you want it to end up) like so:
Javascript Code
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var body = document.getElementsByTagName("BODY")[0];
var img = document.createElement("img");
img.className = 'img-responsive'
img.src = '~/Content/Images/Template 5A Filmstrip.jpg';
body.appendChild(img);
}
You can add a <img> to any element using the jQuery .append() function in the following way:
var imageToAppend = '<img src="http://example.com/img.png" height="200" width="200"/>';
$('#myElementId').append(imageToAppend); //This will append you HTML to the div with id "myElementId"
You can read more about this here: http://api.jquery.com/append/
Happy coding! =]
You should use the element where you need to append (prepend) the image element so the code will look something like:
$("base element selector").append(img);
but you need to consider that the address of the image source may not be correct from the browser point of view - consider the page is hosted in application like http://server.com//applicationgroup/applicationroot/Content/Images/.....jpg may not be pointed with ~/Content/Images/.....jpg you rather need to translate the address to the full server address on the server side.
In my case I just had to remove "~" from:
<img src="~/assets/icons/ic_chevron2.svg" class="rot-90" />
resulting in:
<img src="/assets/icons/ic_chevron2.svg" class="rot-90" />

Use result of function in html img tag

I try to use the result of a javascript function to fill in the 'src' value of IMG tags.
I want to use this on many places in same page, otherwise I think I could use an ID in the IMG tag and change src with getelementbyid.
The idea is to load images depending on the size of the userscreen.
The code which does not give me correct result:
<html>
<head>
<script>
function path_images(image)
{
var s = screen.width;
path = (s<1080) ? "small":"large";
return path + "/" + image;
}
</script>
</head>
<body>
<h1>Some text</h1>
<img alt="error" src=path_images("someimage.png")>
<img alt="error" src=path_images("someotherimage.png")>
</body>
Please tell me how to do this.
You could try this. It selects all elements with tag img and changes eachs SRC. If you want to change the source of one single image you should use ids or any other identifier.
function changeSource()
{
aImgs = document.getElementsByTagName("img");
for ( var index in aImgs )
aImgs[ index ].src = path_images( image_here );
}
Grab the images:
var images = document.querySelectorAll('img');
Convert the nodelist to an array and loop over it updating the src.
Array.prototype.slice.call(images).forEach(function (img) {
img.src = path_images(img.getAttribute('src'));
});
#ron for this purpose you just need to call a function on body onload, what this function will do? this function will very much get the screen width first and after the decision whether there would be small or large it will grab all the images coming at the page along with their src attributes, then loop over each (maybe foreach) of them in the same body onload function and concat the small or large before the path and this will fullfill your requirment.
Well function can't be call on img src tag it can be at onclick event. each javascript function is called at some event.

How to change a website image with javascript?

I'm working with my first Greasemonkey script.
And its for a website that have a logo, i want to change the image to a image i have created, and i wonder how i do this?
like use JavaScript to edit the current html document and replace the image.
Thanks for any help!
Edit: The image is inside a <img> tag, the image i want to change/replace is in this code:
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo" width="170" height="36">
Here is the javascript code i tryed and didnt work:
var myImage = document.querySelector('.fb_logo img');
myImage.src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
var logos = document.getElementsByClassName("fb_logo");
for( var i = 0; i < logos.length; i++ )
{
// true for all img tags with the fb_logo class name
if( logos[ i ].tagName == "IMG" )
{
logos[ i ].src = "http://www.computerweekly.com/blogs/it-downtime-blog/lolcat-tan.jpg"
}
}
Knowing that you can use browser-specific javascript is a plus.
Use querySelectorAll.
var img = document.querySelectorAll('.yourClass')[0];
Note: you're possibly selecting more than one element, so it's returning a nodelist rather than a single node, remember to select the first item in the list.
Better yet, use querySelector
var img = document.querySelector('.yourClass');
Okay, here's a complete Greasemonkey script that swaps the logo image at Facebook under real-world conditions (meaning that the image may be in different places and you have to deal with the container and background images, etc.).
Note that this script looks for the image in two types of locations, and deals with the surrounding HTML, and CSS, if necessary.
Also note that it uses jQuery -- which is a godsend for writing GM scripts.
Finally: note that I avoid Facebook, and only know of the one logo location (plus the one that the OP reports. If there are new/different locations, deal with them in a similar manner.
// ==UserScript==
// #name _Facebook Logo Swap
// #include http://www.facebook.com/*
// #include https://www.facebook.com/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
/*--- Found FB logo at:
"h1#pageLogo a" as a backgound image.
It's reportedly also at: "img.fb_logo.img"
*/
var desiredImage = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
//--- Straight image swap:
$('img.fb_logo').attr ('src', desiredImage);
/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
Since this image is transparent, clear the old BG image.
Also constrain the new img to its container.
*/
$('#pageLogo a').css ('background-image', 'none')
.append ('<img>').find ('img') .attr ('src', desiredImage)
.css ( {width: '100%', height: '100%'} );
find the image tag and replace the src attribute.
var myImage = document.getElementById(idOfImageYouNeedToChange);
myImage.src = "your_image";
Pretty straightforward.
You can do this very simply with jQuery
$('.fb_logo').attr('src','newimage.jpg');
you have to get the reference to your img element first, better use id instead of a class, since getElementsByClassName is not supported in IE until ie9:
with raw javascript (there are many ways of doing this. this is just the one):
var theImg = document.getElementById('imageId');
theImg.src = 'someNewPath'
with something like jQuery(js library) - you can easily select by class or by id or by tag etc:
$('.yourPicClass').attr('src', 'someNewPath')
How about using the DOM to find that specific attribute and change it to whatever?
<html>
<body>
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var yerImg = document.getElementsByTagName("img");
yerImg[0].setAttribute("src", "http://goo.gl/JP8bQ");
</script>
</html>
querySelector:
return the first matching Element node within the node’s subtrees. If there is no such node, the method must return null.
querySelectorAll:
return a NodeList containing all of the matching Element nodes within the node’s subtrees, in document order. If there are no such nodes, the method must return an empty NodeList.
The Use :
var element = baseElement.querySelector(selectors);
var elementList = baseElement.querySelectorAll(selectors);
Sample :
<html>
<body>
<img class="fb_logo" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var myImageList = document.querySelectorAll('.fb_logo');
myImageList[0].src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
</script>
</html>

How to update HTML element with jQuery and Galleria?

I am using Galleria for a slideshow. I want to place a small, 'Larger' link beside the stage.
I have this code for the 'Larger' button:
this.fullres = this.create('div', 'fullres');
this.get('fullres').innerHTML = 'Larger';
this.appendChild('fullres', this.fullres);
I have this code that assigns every <img>'s rel= tag to the full sized image URL from the page's custom field:
<img ... rel="<?=$attachments[$i]['fullres']?>" />
With JQuery, I am hoping to pull the active image's rel= tag value and append the .fullres href tag. This is the code I have so far, but it doesn't work:
var title = $(.images).attr('rel'); // pulls the fullres url from the rel tag
$('.galleria-fullres').attr('href', ); //append the galleria fullres href with the rel info
Galleria doesn't really work like that. But what you can do, is to create a button to enter fullscreen and have a larger image in fullscreen.
Something like this:
$('#galleria').galleria({
// other galleria options here
dataConfig: function( img ) {
// get the fullscreen image
return {
big: $( img ).attr('rel')
};
}
});
var galleria = Galleria.get(0);
$('#fullscreen-button').click(function() {
galleria.enterFullscreen();
});
I have to say I can't see how this would work as it is...
Do you know you have a typo at: $(.images)? Should be $('.images').
And have you left out the second parameter at $('.galleria-fullres').attr('href', ); on purpose? Shouldn't this be $('.galleria-fullres').attr('href', title); ?
How can the jquery work by referencing the elements by classes? You are getting an array of elements, not just one. I guess this is only an excerpt of your code? Am I missing something?
Could you perhaps post the html of a sample of these elements as seen in the browser? It should be a pretty easy thing, but I really can't see the whole picture with those lines only.

Categories

Resources