find an image name and replace it with a different source - javascript

I am writing a chrome extension to replace all the occurrences of certain set of image ( I have the image names) and replace it with another image (src)
I need to find all the occurrences of a certain image name in a website and replace the src of the image with a custom image.
I can find the image name in <img> tags with the following snippet
var key = 'img[src*="' + src + '"]';
var img = $(key);
img.attr('src', 'http://blah.blah/a.png);
Problem occurs when the image is set as background-image or as a css property.
Is it possible to scan the DOM with jQuery (recursively in all the attached style sheets) and replace all the occurrences of the image with the target url? If it is possible, can anyone point me in the right direction?

I think this could be like this, hope this will help you
$(document).ready(function(){
$("*").each(function(){
var bgImge = $(this).css('background-image');
if(bgImge.indexOf('yourImageName') > -1)
{
$(this).css('background-image', 'newImage');
}
});
});

You can change all inline background images with this:
$("[style*=background-image]").css('background-image', function(i, oldimg) {
return oldimg.indexOf(src) == -1 ? oldimg : 'url(http://blah.blah/a.png)';
});
Changing background images in the CSS is trickier.
var ss = document.styleSheets;
for (var i = 0; i < ss.length; i++) {
var rules = ss[i].cssRules;
for (var j = 0; j < rules.length; j++) {
var rule = rules[i];
if (rule && rule.type == CSSRule.STYLE_RULE && rule.style.backgroundImage.indexOf(src) != -1) {
rule.style.backgroundImage = 'url(http://blah.blah/a.png)';
}
}
}

Tested on current page, working fine.
var src = 'http://cdn.sstatic.net/stackoverflow/img/sprites.svg?v=a7723f5f7e59';
$('*').each(function(){
if( $(this).css('background-image').indexOf(src)!=-1){
console.log('Found',this);
$(this).css('background-image','url(http://blah.blah/a.png)');
}
});

You could manually run through each to check it's value:
$("*").each(function() {
var b = $(this).css("background-image") || $(this).css("background");
// check if 'b' has the image name
})

Related

Get Href Link; if JPG to skip

I've created a loader for my website (the whole front end is custom,so as of right now i can edit about 95% of everything I have except for woocommerce plugin).
Super simple one, it follows this logic, if the anchor is an # or the page itself it wont do anything (which is what I wanted) but the woocommerce plugin to generate my image gallery is a link that isn't the page itself or a #. Which means I need to collect the path-name of the extension that if it ends on jpg png or any image file to continue; and skip over the rest of the animation and allow the plugin to run its course.
Ive use Barba JS, SWUP and other animations with woocommerce and this is the only one that doesnt interrupt or have so many conditions with woocommerce.
function fadeInPage() {
if (!window.AnimationEvent) { return; }
var fader = document.getElementById('fader');
fader.classList.add('fade-out');
}
document.addEventListener('DOMContentLoaded', function() {
if (!window.AnimationEvent) { return }
var anchors = document.getElementsByTagName('a');
******* for (var idx = 0; idx < anchors.length; idx += 1) {
if (anchors[idx].hostname !== window.location.hostname || anchors[idx].pathname === window.location.pathname) *******
{
continue;
}
anchors[idx].addEventListener('click', function(event) {
var fader = document.getElementById('fader'),
anchor = event.currentTarget;
var listener = function() {
window.location = anchor.href;
fader.removeEventListener('animationend', listener);
};
fader.addEventListener('animationend', listener);
event.preventDefault();
fader.classList.add('fade-in');
});
}
});
window.addEventListener('pageshow', function (event) {
if (!event.persisted) {
return;
}
var fader = document.getElementById('fader');
fader.classList.remove('fade-in');
});
I starred what i need changed. the animation works, the page transition works. I need the animation to recognize if the a tag ends with an jpg or png to skip and not do the animation and treat the link as if the animation wasn't there.
Never used woocommerce so I don't totally understand the use case, but you can get the file extension of a link like so:
for (var idx = 0; idx < anchors.length; idx += 1) {
let fileType = anchors[idx].href.split('.').pop();
//Do whatever
}
Or if you want to compare it to a preset list of extensions you can use a regex:
for (var idx = 0; idx < anchors.length; idx += 1) {
if (anchors[idx].href.match(/\.(jpg|png)$/)) {
//Do whatever
}
}

Use javascript selectors without jQuery to select images

I have some images like this:
<img src="http://127.0.0.1/test/images/cat01.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat02.png" alt="00" class="cat_img">
<img src="http://127.0.0.1/test/images/cat03.png" alt="00" class="cat_img">
and I want to select the image names (cat01.png, cat03.png and cat03.png) with javascript (without jQuery).
How can I do that ?
I have tried :
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
console.log('Images '+images);
Thanks for help.
Or like this (no need to use Array.prototype.slice)
var images = Array.prototype.map.call(
document.querySelectorAll(".cat_img"),
function(img) {
var src = img.src,
lastIndex = src.lastIndexOf('/');
return src.slice(lastIndex + 1);
});
You can loop over your images array using map and return the part of the src attribute that you want (everything after the last /):
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
var imageNames = images.map(function( image ) {
return image.src.substring( image.src.lastIndexOf("/") + 1 );
} );
console.log(imageNames);
jsfiddle
Here is a simple example using regex with a loop.
var images = Array.prototype.slice.call(document.getElementsByClassName('cat_img'));
for(i = 0; i < images.length; i++) {
console.log(images[i].src.replace(/.+\//, ''));
}
jsfiddle
So to build your array of names, just replace the console.log(...) line with images[i] = images[i].src.replace(/.+\//, '')

How to check if an element contains an image?

How do I check to see if an element contains an image. Can't I do something like this
if(document.getElementById("image").src == myImage.src)
function hasImage(element, src) {
var images = element.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
if (images[i].getAttribute("src") == src) {
return true;
}
}
return false;
}
console.log(hasImage(document.getElementById("image"), myImage.src));
If your browser supports it, you can use element.querySelector()
var img = document.getElementById("image")
.querySelector("img[src='" + myImage.src + "']");
console.log(img ? "Found" : "Not found");
Are you trying to check if an img tag with the id "image" has a src attribute equal to a different img tag? If so try the following
if (document.getElementById('image').getAttribute('src') === myImage.getAttribute('src)) {
...
}
If you just want to see if it has an src attribute at all then you can do the following
if (document.getElementById('image').getAttribute('src')) {
...
}

How to populate alt fields with the src of an image for all images on page

I am working on a site that has a page that will have a couple hundred thumbnails. I would like to have the filenames (the src) of the images populate the alt fields. So for example, I currently have the thumbnails as follows:
<img src="images/thumb1.jpg" />
I would like to populate the alt fields with the filename. So, the desired result would be:
<img src="images/thumb1.jpg" alt="thumb1" />
Is there a way I can automatically generate these alt tags using the images src?
Any suggestions are appreciated. Thank you for the help!
An untested, first guess, would be:
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
images[i].alt = images[i].src;
}
JS Fiddle demo.
Just to demonstrate how much easier this can be, with a JavaScript library, I thought I'd also offer the jQuery demo too:
$('img').each(
function(){
this.alt = this.src;
this.title = this.src;
});
jQuery-based JS Fiddle demo.
Edited because I'm an idiot...
I forgot to point out that you'll need to wait for the window to finish loading (or, at least, for the document.ready event), so try it this way:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i = 0; i < numImages; i++) {
images[i].alt = images[i].src;
images[i].title = images[i].src;
}
}
And change the opening body tag to:
<body onload="makeAlt">
JS Fiddle demo.
Edited to address the OP's final question:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
var newAlt, stopAt;
for (i = 0; i < numImages; i++) {
newAlt = images[i].src.split('/').pop();
stopAt = newAlt.indexOf('.');
newAlt = newAlt.substring(0,stopAt);
images[i].alt = newAlt;
images[i].title = newAlt;
}
}
JS Fiddle, though I suspect there's a far more concise way...
To get the file name you could add to David Thomas's code...
var name = images[i].getAttribute('alt').split('/');
name = name[name.length-1].split('.')[0];
So that you end up with...
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
var name = images[i].getAttribute('src').split('/');
name = name[name.length-1].split('.')[0];
images[i].setAttribute('alt') = name;
}
(Also amazingly untested)
Here it is, with some simple DOM operations and a dash of regex magic:
var imgs = document.getElementsByTagName('img');
// This will extract the file name (minus extension) from the image's `src`
// attribute. For example: "images/thumb1.jpg" => "thumb1"
var name_regexp = /([^/]+)\.[\w]{2,4}$/i;
var matches;
for ( i = 0; i < imgs.length; i++ ) {
matches = imgs[i].src.match(name_regexp);
if ( matches.length > 1 ) {
imgs[i].alt = matches[1];
imgs[i].title = matches[1];
}
}
See JSFiddle for a demo.
var images = document.getElementsByTagName("img");
var count = images.length;
for (i=0; i<count; i++){
var src = images[i].getAttribute("src");
var path = src.split("/");
var fullname = path[path.length - 1];
var name = fullname.split(".");
var result = name[0];
images[i].setAttribute("alt") = result;
}
I think the real questions you should be asking is will all this actually help my SEO, because I assume that is the reason why you would like your alt tags populated?
There is some evidence that Google is getting better at reading Javascript, but will it run the scrip before it crawls the pages and add the alt text then index the page with that alt text and consider that alt text to provide additional value outside of the keywords it already found in your file names, especially considering that it rendered the script so it will probably know that the alt is just being copied form the file name. Or will Google simply index all the html and not even bother trying to run the javascript?
I would be interested to hear any additional insight others may have on this.
I personally feel there is a low probably that this will end up helping your SEO. If you are using a content management system you should probably be looking at how to add alt text via PHP by taking the variable for the page heading or title and inserting that to the alt text.
Unless you don't care about your SEO and are really doing this for text readers, then forget everything i just said.

How to stop Javascript from showing default image and only text for link?

The Javascript below has a default image, but I would like display text "only text url" for this link instead of this button at this link http://developer.mixi.co.jp/wp-content/uploads/2010/09/bt_check_1.gif that this script defaults to. Is this possible?
<div>
only text url
<script type="text/javascript" src="http://static.mixi.jp/js/share.js"></script>
</div>
Assuming this is legal (it may not be legal to embed this script in your site if you make modifications to it), we can decompress the script using an online JavaScript beautifier. The result is this:
http://www.jsfiddle.net/T4Rrh/
The bit we're interested in is the last for loop there, where each button is processed. We can safely remove a most of the image generation and protocol sniffing (an unnecessary practice, by the way) to reduce the weight of the code:
var type = (button["button"] || "button-1.png").split("-");
var prefix = ("https:" == document.location.protocol) ? "https://mixi.jp/" : "http://static.mixi.jp/";
if (!type || type.length < 2) type = ["button", "1.png"];
if (type[1].indexOf(".") == -1) type[1] += ".png";
var src = (type[0] == "button") ? [prefix, "img/basic/mixicheck_entry/bt_check_", type[1]] : (type[0] == "icon") ? [prefix, "img/basic/mixicheck_entry/icon_mixi_", type[1]] : [prefix, "img/basic/mixicheck_entry/bt_check_1.png"];
src = src.join("");
and
var img = document.createElement("img");
img.setAttribute("src", src);
img.style.border = "0";
var element = button.element;
for (var j = element.childNodes.length - 1; j >= 0; j--) {
element.removeChild(element.childNodes[j]);
}
element.appendChild(img);
should be both removed. You can then minify and save the code, then serve it yourself in your page. Here's what the cleaned up code looks like: http://www.jsfiddle.net/XrYLX/
Second Method:
Using CSS, we first remove the part of the JavaScript which removes all child nodes of the button element, so the text inside the button is not removed:
for (var j = element.childNodes.length - 1; j >= 0; j--) {
element.removeChild(element.childNodes[j]);
}
We then apply some CSS to hide the image:
.mixi-check-button img {
display: none;
}
See: http://www.jsfiddle.net/T4Rrh/1/.
Copy that script to your site and remove element.appendChild(img); at the beginning of the last line.

Categories

Resources