Replace images with jQuery in userscript - javascript

I'm currently working on a userscript, but I have a problem.
I'm trying to replace an image with another one.
I thought I could do it this way:
$(".subforumicon.ajax_mark_read").each(function() {
$(this).html($(this).html().replace(/http:\/\/x\.hackforums\.net\/images\/modern_pl\/minion.gif/g, "http://megaviews.net/hf/designcostumizer/themes/green/minion.png"));
});
However, this will do nothing. When I paste this code in the javascript console, it just displays all img-tags with this picture:
I don't want to replace everything by using $("body").html(), as this can cause problems with the website (somehow).
Before I started working with jQuery, I used document.body.innerHTML, what caused issues on the page, but with document.getElementById() it worked, so I don't think it was my fault. ;)
I'm quite new to jQuery, so could somebody please explain me why my above code doesn't work?

It does not work because the selected elements are img and there is nothing below the img elements.. as .html() selects or sets the INSIDE content (like innerHTML). not outerHTML so you cannot access the attributes of the img element itself by this mean.
You should work on the img's src attribute as already proposed in other posts.

Use .prop()
you need $('img') as you are changing image src only.
so replace img attribute src only.
why traverse through all full html you need to focus on src property only.
$('img').prop('src', function (_, old_src) {
return old_src.replace(/http:\/\/x\.hackforums\.net\/images\/modern_pl\/minion.gif/g, "http://megaviews.net/hf/designcostumizer/themes/green/minion.png");
});
or better if you want to change all images attribute src
$('img').prop('src','http://x.hackforums.net/images/modern_pl/minion.gif');

Related

Sharepoint image referencing

I can't seem to find the correct encapsulating or prefix syntax for referencing an image located in xxxx site collection.
Right now I have three variations of one image that will be applied to the footer. And these variants are selected based on the site collection, so I can't directly set the image to the masterpage (Unless I want to make three masterpages, which is just overkill for a single image).
I have tried going about this using Javascript to set the source of an img element and CSS to set the url of a container element's background-image. Both are failing me.
In Javascript, I have tried setting the src attribute of my element to:
"<SharePoint:ProjectProperty Property='SiteUrl' runat='server' />/_catalogs/masterpage/Images/myimage.gif;"
"<% $SPUrl:~sitecollection/_catalogs/masterpage/Images/myimage.gif %>";
"~sitecollection/_catalogs/masterpage/Images/myimage.gif";
and repeated the same with CSS for background-image property to a div element. But all I ever get is errors or it doesn't translate the sharepoint code.
Does anyone have any idea what else I can try?
check these URLs for reference -
http://www.vrdmn.com/2011/08/javascript-lmenubaseurl-varaible-for.html
http://johnliu.net/blog/2012/2/3/sharepoint-javascript-current-page-context-info.html
http://blogbaris.blogspot.com/2013/01/getting-web-url-with-sharepoint-2010.html
and try the below method to get the URL.
<%script type="text/javascript">
var url = "<%= SPContext.Current.Site.Url %>";
</script>
Hope this helps!
Where exactly is this image stored? Is it in the default "Images" library of a publishing site? If so, you've got the wrong path. It would be "/PublishingImages/myimage.gif".

JQuery .attr won't retrieve or change values

I'm trying to change HTML attributes using jQuery, but no matter what I do, I can't get anything to work with jQuery's .attr().
For testing, I've written
alert($("#logo").attr("title"));
and even though I have an img with id="logo" and a title, the alert remains blank.
My full method:
function switchVideo(videoID) {
var videoPlayer = document.getElementById("example_video_1");
videoPlayer.src = "video/Occam.webm";
videoPlayer.load();
$("#example_video_1").attr("poster", "video/ss.png");
//Doesn't work:
alert($("#logo").attr("title"));
$("#logo").fadeOut();
videoPlayer.play();
}
My fade out works, so I know I imported jQuery correctly.
I've gotten it working in another document, so there must be something else in the document messing it up. Does anyone know why this simple method won't work?
You can see the source page at http://jrstrauss.net/temp/create.html
Your div has the id logo, not the img.
Try:
$("#logo img").attr("title")
You should be using $.fn.prop for that now: http://api.jquery.com/prop/
You should use prop if you are using a recent version of jQuery.
You can also try this according to your HTML:
alert( $("#logo a img").attr("title") );
Demo
You have the following markup with id logo
<div id="logo">
......
</div>
Now, you are trying to run jQuery's .attr method by following code.
$("#logo").attr("title");
as you may know .attr method retrieves attribute value of the given element but that <div> doesn't have a attribute named title. so to confirm this, try retrieving attribute that does exist, for example id. so try this
alert($("#logo").attr("id"));
This will return the value of attribute. the important thing to note is jQuery looks for attributes of given element only, It doesn't scan child elements.
So, to make it work in your case. You need to do the following
alert($("#logo img").attr("title"));
Hope it helps

constrain image width in javascript link

How to constrain image width in javascript link? (As you would easily do in HTML.) The following code is not working. The image sources at 250px, so can't a width attribute be put in the script tag to constrain it to 191px? Thank you.
(I am using single quote marks here because the whole script tag code is contained within double quotes.)
<script type='text/javascript' language='javascript' src='http://www.dpbolvw.net/29102g73tvx-63wx9IOQJRNJM?target=_blank&mouseover=Y' width='191'></script>
The script you're including is programmatically adding an <img> to your document:
document.write("<a href=\"javascript:submitCJ10909759X391\
(\'CJ10909759X391\',null);\"><img src=\"http://www.yceml.net\
/0063/10909759-1.jpg\" width=\"250\" height=\"250\"\
alt=\"Travel related banner\" border=\"0\"/></a>");
You can modify the width of the image in one of two ways:
Modify the script that you're loading, or, if that's not possible;
Run your own script afterwards and use it to locate the <img> that was appended.
Unfortunately, the script doesn't give the <img> an id whereby you could easily find it in the DOM. If this is the way you want to go, I leave it up to you to find an alternative to locate the <img> in your DOM tree.
Per the conversation we had, it looks like this JS is loading an image.
The only way to set a width attribute on this image would be for the script to support that feature, where you could perhaps pass it in as a querystring. Alas, it looks like this script does not do that.
My suggestion is to wrap the script tag (which renders an IMG tag) and then use CSS to handle the width:
<div id="myImage"><script.../></div>
#myImage img {width: 191px;}

Finding images on page that have a specific filename with jquery

I need to do a check on a page to check if certain images have loaded ie. not returned 404. If they arent available I want to replace the image with a default images.
I am aware I can assign an onerror handler to the images.
Firstly I need to use a selector to find all the images that have a source which contains the following image name -> /folder/Product_1234_P.jpg OR /folder/Product_9876_Q.gif
Any ideas how I can create a high performance selector that I can use to find such images so that I can check if the images loaded, if not replace the image name with: Product_Default_P.jpg or Product_Default_Q.gif
Any help or advice would be great.
You can use the image's error handler and the attribute contains selector like so:
$("img[src*=Product]").error(function() {
$(this).attr('src', 'notfound.jpeg');
});
$('img[src*="substring"]')
It's an attribute selector. Check it out http://api.jquery.com/attribute-contains-selector/
I guess you mean something like
$("img[src^=/folder/Product_][src$=_P.jpg]")
i.e. "Find all img with a src starting with "/folder/Product_" and ending with "_P.jpg".

How can I select an <img> element programmatically using JavaScript?

I have an <img> in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript?
I only need it to work in Mozilla, but any and all information is welcome.
EDIT: The reason I want to select the image is actually not so that it appears highlighted, but so that I can then copy the selected image to the clipboard using XPCOM. So the img actually has to be selected for this to work.
Here's an example which selects the first image on the page (which will be the Stack Overflow logo if you test it out on this page in Firebug):
var s = window.getSelection()
var r = document.createRange();
r.selectNode(document.images[0]);
s.addRange(r)
Relevant documentation:
http://developer.mozilla.org/en/DOM/window.getSelection
http://developer.mozilla.org/en/DOM/range.selectNode
http://developer.mozilla.org/en/DOM/Selection/addRange
You might also want to call s.removeAllRanges() before s.addRange(r).
What, exactly, are you trying to do? If you're using XPCOM, you're presumably writing an application or an extension for one; can't you just get the image data and put it on the clipboard directly?
My personal choice for selecting elements is jquery:
Then to get the element of your choice is:
$("img#YOURIMAGEHERE").focus();
You can swap the source of the image, as in img.src = "otherimage.png";
I actually did this at one point, and there are things you can do to pre-load the images.
I even set up special attributes on the image elements such as swap-image="otherimage.png", then searched for any elements that had it, and set up handlers to automatically swap the images... you can do some fun stuff.
Sorry I misunderstood the question! but anyways, for those of you interested in doing what I am talking about, here is an example of what I mean (crude implementation, I would suggest using frameworks like jQuery to improve it, but just something to get you going):
<html>
<body>
<script language="javascript">
function swap(name) {
document.getElementById("image").src = name;
}
</script>
<img id="image" src="test1.png"
onmouseover="javascript:swap('test0.png');"
onmouseout="javascript:swap('test1.png');">
</body>
</html>
The basic idea of the "highLight" solution is ok, but you probably want to set a "static" border style (defined in css) for the img with the same dimensions as the one specified in the highLight method, so it doesn't cause a resize.
In addition, I believe that if you change the call to "highLight(this)", and the function def to "highLight(obj)", then you can skip the "document.getElementById()" call (and the specification of the "id" attribute for "img"), as long as you do "obj.style.border" instead.
You probably also need to spell "highLight" correctly.
Give the img tag an ID. Use document.getElementById('id').
<script type="text/javascript" language="javascript">
function highLight()
{
var img = document.getElementById('myImage');
img.style.border = "inset 2px black";
}
</script>
<img src="whatever.gif" id="myImage" onclick="hightLight()" />
EDIT::
You might try .focus to give it focus.

Categories