I have two separate images for each 'active' and 'inactive' link on my page. Each link toggles a different article on my web page.
<img src="/img/active.png" />
<img src="/img/inactive.png" />
I'm initially displaying all the inactive images on my page, but would like to display the active image respective to the link a user clicks.
Note * Each link, both active and inactive, will have a unique image url
<a href="#">
<div>
Click here for foo
<img src="/img/inactive-123.png" />
</div>
</a>
<a href="#">
<div>
Click here for bar
<img src="/img/inactive-345.png" />
</div>
</a>
There will potentially be 100+ links on my page, so I am looking for the most efficient & maintainable way to do this in jquery. I've thought about indexing these images with a number, but that could easily lead to incorrect associations between my articles - any ideas?
Sorry for clear JS, not JQuery as you mentioned
var tab = document.getElementsByTagName("img");
for (var i = 0; i < tab.length; i++){
tab[i].addEventListener('click', function () {
if (this.src.indexOf("inactive") !== -1){
this.src = this.src.substring(0, this.src.length -12)
this.src += "active.png"
}
else {
this.src = this.src.substring(0, this.src.length -10)
this.src += "inactive.png"
}
})
}
It will work as long as inactive.png or either active.png are on the end of the src value.
You can accomplish this without jQuery pretty simply. I'm assuming that the structure of the elements inside the <a> will be the same as you wrote. But you can create a function that takes this (a element) and the src you want to replace the inner img tag with. Of course you'll want to edit the function to be a bit more safe of about handling errors, e.g. index out of range exceptions.
activateImg = function (elm, imgSrc) {
elm.children[0].children[0].src = imgSrc;
}
<a href="#" onclick="activateImg(this, 'https://placeholdit.imgix.net/~text?txtsize=33&txt=ACTIVE%20FOO&w=350&h=150')">
<div>
Click here for foo
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=INACTIVE%20FOO&w=350&h=150" />
</div>
</a>
<a href="#" onclick="activateImg(this, 'https://placeholdit.imgix.net/~text?txtsize=33&txt=ACTIVE%20BAR&w=350&h=150')">
<div>
Click here for bar
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=INACTIVE%20BAR&w=350&h=150" />
</div>
</a>
Edit:
If you want to swap the images back and forth just pass in both image links and swap depending on which one is the current src. http://plnkr.co/edit/LUDZEQF1AHXEZ7L83Fyb?p=preview
Edit2: I just re-read your comment and I think only one image can be active at a time. For that you could use an attribute to manage the state like data-active. I'll have an example soon.
If your links route to another page, something like the following should work:
$(function () {
var pathname = window.location.pathname.replace(/\//g, "");
$('a[href=' + pathname + '] img').attr('src', "/img/active.png");
});
Or do you need the image to change without refreshing the page?
I came up with a simple solution I'm happy with; I have created two data attributes on each image
<img
src=""
data-inactive-src="/inactive-123.png"
data-active-src="/active-123.png"
/>
<img
src=""
data-inactive-src="/inactive-345.png"
data-active-src="/active-345ng"
/>
Then when it comes time to swap the active for the inactive image, I do this
var currentIcon = $("#link-"+target).find('a div img') // don't worry about this line
var allIcons = $('a div img');
/** This section SHOULD keep track of the last
icon changed and change it back to inactive instead of looping through each element**/
allIcons.each(function(index) {
$(this).attr("src", $(this).data("inactive-src"));
});
/** Set the active icon image for the current target **/
currentIcon.attr("src", currentIcon.data("active-src"));
The each() loop will have to be swapped out, but this gives me perfect control of the active/inactive images. If you see any flaws with this please let me know!
Related
I'm trying to modify specific images as the site displays a lower resolution file than the original, and also replace the link href for that image -- appending something to the end of that link to make it downloadable.
The website in particular, does not properly send the information about the image to the browser when you right click/save (file saves as content.jpg), but they have a download link which does properly send the filename to the browser (All it does is append &dl=1 to the end of the URL)
I have found some example code, and modified it to do the img src changes I require, but am having issues appending to the link href.
There are many types of links on the page so specific URL replacement is required:
Clickable Links all over page (Don't touch):
example.com/view/UNIQUEID
Image Src (Low Res): example.com/subdir/preview?page=UNIQUEID
Image Src (Original Res): example.com/subdir/content?page=UNIQUEID
I only wish to change the image sources from content/preview to content/content to display the full resolution image in the browser, but also add an href link (this can be copied from the img src as its the same link, but also append something to the end of it without affecting any other links.)
Here's what I have so far which works for replacing the specific img src:
image = document.getElementsByTagName("img");
for (i = 0; i < image.length; i++) if (image[i].parentNode.href) {
//Remove onclick attribute, cancelling their own Image Viewer
image[i].parentNode.removeAttribute('onclick');
//Replace regular sized preview image, with the full sized image
image[i].src = image[i].src.replace('example.com/subdir/preview?page=','example.com/subdir/content?page=');
image[i].parentNode.removeAttribute('width');
image[i].parentNode.removeAttribute('height');
}
Now I've found that adding
image[i].parentNode.href = image[i].src + '&dl=1';
at the end of my current script works. But it affects every image, so it breaks a lot of other things.
Any suggestions to simply append &dl=1 to the end of the now replaced 'subdir/content?page=UNIQUEID' href links?
TLDR:
Looking to change:
<a href="http://example.com/subdir/content?page=12345" onclick="imageviewer.open(); return false;">
<img src="http://example.com/subdir/preview?page=12345&filename=this+is+the+filename.jpg">
</a>
into:
<a href="http://example.com/subdir/content?page=12345&dl=1">
<img src="http://example.com/subdir/content?page=12345&filename=this+is+the+filename.jpg">
</a>
This question is almost a duplicate of: How to relink/delink image URLs to point to the full image?
The trick is to use querySelectorAll() (or jQuery) to fine-tune which images are processed.
Also, I recommend not changing the image source (keeps page fast and saves bandwidth), but just rewriting the link. Once the link is rewritten, you can right-click to save larger versions of just the pics you are interested in. Or, you can then use the excellent DownThemAll extension to bulk download images by link.
In your case, code like this should work:
var thumbImgs = document.querySelectorAll ("a > img[src*='subdir/preview?']");
for (var J = thumbImgs.length-1; J >= 0; --J) {
var img = thumbImgs[J];
var link = img.parentNode;
var lnkTarg = link.href + "&dl=1";
link.href = lnkTarg;
link.removeAttribute ('onclick');
//-- Not recommnded to change thumbnail...
//var imgTarg = img.src.replace (/\/preview/, "/content");
//img.src = imgTarg;
}
<a href="http://example.com/subdir/content?page=12345" onclick="alert('I shouldn\'t fire on click!'); return false;">
<img alt="Target img 1" src="http://example.com/subdir/preview?page=12345&filename=filename_1.jpg">
</a><br>
<a href="http://example.com/subdir/content?page=aaa" onclick="alert('I shouldn\'t fire on click!'); return false;">
<img alt="Target img 2" src="http://example.com/subdir/preview?page=aaa&filename=filename_2.jpg">
</a><br>
<a href="http://example.com/some/random/link" onclick="alert('I should still fire on click!'); return false;">
alt="Img shouldn't be altered" <img src="http://example.com/some/random/image.jpg">
</a>
I want to embed an image inside an tag after the image on tag loaded.
So the sequence goes like this...
<a id="anchorID">
<img onload="MyFunc(anchorID)>IMAGE1</img>
//..After image 1 loaded add
<img>IMAGE2</img>
</a>
<script>
function MyFunc(anchorID)
{
var anchorElement = document.getElementById(anchorID);
//I want to create an image tag inside the anchorElement
}
</script>
Thanks for the help.. T_T
Here's a solution, just add onload="addNextImage('#id_in_which_to_add_new_image', 'second_image_url')" to the image you want to load first. In the next example, ignore the width and style (I put them there to be able to test the functionality, making the image smaller so I don't need to scroll to see the behavior - I chose a huge image to make sure everything works as it should, and the border makes it appear sort of like a progress bar =)
<script>
function addNextImage(selector, url) {
var where = document.querySelector(selector);
if (where) {
var newImage = document.createElement('img');
newImage.src = url;
where.appendChild(newImage);
}
}
</script>
<a id="anchorID">
<img onload="addNextImage('#anchorID', 'http://animalia-life.com/data_images/wallpaper/tiger-wallpaper/tiger-wallpaper-01.jpg')" src="http://hubblesource.stsci.edu/events/iyafinale/support/documents/gal_cen-composite-9725x4862.png" width="400px" style="border: 1px solid black" />
</a>
This should work on most browsers today: IE8+ (as long as you use basic CSS2.1 selectors as the first argument), and pretty much everything else in use. (IE8+ because it depends on querySelector)
I think what you are looking for is
Javascript appendChild()
var node = document.createElement("img");//Create a <img> node
node.src="SomeImageURL";
firstImage.appendChild(node);
JQuery append()
$("#firstImageID").append("<img src="SomeImageURL"/>");
see links for more info
Javascript
jQuery
You can use the following to add an image to the anchor tag
function MyFunc(anchorID) {
var anchorElement = document.getElementById(anchorID);
if (anchorElement) {
//I want to create an image tag inside the anchorElement
var img = document.createElement("img");
img.setAttribute("src", "yourImagePath");
anchorElement.appendChild(img);
}
}
Hope that helps.
Is it possible to add a lightbox effect automatically to every image which is embedded like this
<img class="full-img" src="/blog/content/images/2014/Jun/biking_hwy1.jpg" alt="">
to this
<img class="full-img" src="/blog/content/images/2014/Jun/biking_hwy1.jpg" alt="" title="">
after the page loaded successfully?
I would like to enable this on a Ghost CMS installation with JQuery support.
Thanks in advance!
You could have Javascript on every image in the page and then alter the attributes as necessary. Not necessarily the best approach (doing it server-side is preferred), but it can work. You will also, most likely, need to re-instantiate the lightbox plugin to reparse the page after you go through the images.
var img = jQuery("img");
img.each(function() {
var element = jQuery(this);
var a = jQuery("<a />", {href: element.attr("src"), "data-lightbox": "test"});
element.wrap(a);
});
http://jsfiddle.net/ak74A/1/
You'll need to add your own customized properties, but you get the idea.
additional to Jason idea, if you want to add lightbox to images without an anchor tag parent, we can add an if statement to check if the img parent is an anchor tag.
var img = jQuery("img");
img.each(function() {
var element = jQuery(this);
if( this.parentElement.tagName != "A" ){
var a = jQuery("<a />", {href: element.attr("src"), 'data-lightbox': 'Article image'});
element.wrap(a);
}
});
I have fancybox opening when I click on the "main image" area in my gallery, and no matter what image is open fancybox always starts at the first image in the gallery. For example when a user clicks on the 4th image thumbnail, it loads into the "main image" area correctly, but when clicking on the main image fancybox starts from the beginning.
I understand why it's doing this, because the main image area is wrapped in:
<a rel="gallery" class="fancybox" href="#hover0"> <img/> </a>
But what I would like to happen is to have the href '#hover0' change to #hover2, #hover3, #hover4 etc when the corresponding image is loaded in the main area. Not sure how to go about doing this.
Test Page: http://www.pixlsnap.com/j/testb.php
Alright, so I have tested this by saving your whole page (along with all the resources linked to your live site, so glad the images had a direct path), you could do the following, but before I go to that there is a script error that you need to correct:
$(function(){
// Bind a click event to a Cloud Zoom instance.
$('#1').bind('click',function(){
^ You have not closed this function correctly, it needs an extra }); at the end.
Now there are 2 things you need to do for your problem:
1) Paste the following code above the function I mentioned previously (the order matters so it needs to be above it):
$(document).ready(function(){
$('#imgconstrain img').on('click',function(){
$new_hoverid = $('img.cloudzoom-gallery-active').attr('id');
$('#1').closest('a').attr('href','#'+$new_hoverid);
});
});
To explain what this code is doing, when the big image is clicked, we are going to get the active image, in case you haven't noticed, when you click on a thumbnail it gets the class cloudzoom-gallery-active. So, on click of the bigger image, we are going to retrieve the id of the thumbnail with the cloudzoom-gallery-active class.
Now, since we are getting the id attribute, each image should have a unique id. So here we go for the second part:
2) Give your thumbnails image a unique id like:
<li><img class = 'cloudzoom-gallery' id="hover1" src ="http://brecksargent.com/slideshowpro/p.php?a=eXt1NExlZT1uemwuIjItOjI6Hys4OzouNio%2BNC4iKyAiPjQjJjs%2FNCY%2BLiY0&m=1383849642" alt ="LIG Hippie Commune" data-cloudzoom = "useZoom: '.cloudzoom', image:'http://brecksargent.com/slideshowpro/albums/album-16/lg/lig5_on.jpg', zoomImage:'http://brecksargent.com/slideshowpro/albums/album-16/lg/lig5_on.jpg' "> </li>
<!-- ^ here -->
<li><img class = 'cloudzoom-gallery' id="hover2" src ="http://brecksargent.com/slideshowpro/p.php?a=cX12XnxkJXl0bSczJSgwOzIDOjY5OyYzKzE8LTI%2BMiU%2BJzE%2FOicjKD8nNyM%3D&m=1383853420" alt ="Dunno weird though" data-cloudzoom = "useZoom: '.cloudzoom', image:'http://brecksargent.com/slideshowpro/albums/album-16/lg/dod_on.jpg', zoomImage:'http://brecksargent.com/slideshowpro/albums/album-16/lg/dod_on.jpg' "> </li>
<!-- ^ here -->
...till hover6 and that's it.
Let me know if that works for you and feel free to ask if the explanation wasn't clear enough ^-^
Edits:
So as per the comments, here's a few things to be done:
1) In your this anchor tag:
<div id="imgconstrain">
<a rel="gallery" class="fancybox" href="#hover0">
<img class = "cloudzoom" id="1" src =
Take out rel="gallery" (this is the reason fancybox is showing from start on click of next) and remove fancybox class and instead add open-fancybox (the reason for this is coming later)
2) All these lines:
<script type="text/javascript">
function displayCaption() {
var caption = document.getElementById('caption');
caption.innerHTML = this.alt;
}
document.getElementById('1').onclick = displayCaption;
document.getElementById('2').onclick = displayCaption;
//....
</script>
is not needed, we will do this in a smaller way
3) Like I mentioned previously, please add the ids here:
<li><img class = 'cloudzoom-gallery' id="hover1" src ="http://brecksargent.com/slideshowpro/p.php?a=eXt1NExlZT1uemwuIjItOjI6Hys4OzouNio%2BNC4iKyAiPjQjJjs%2FNCY%2BLiY0&m=1383849642" alt ="LIG Hippie Commune" data-cloudzoom = "useZoom: '.cloudzoom', image:'http://brecksargent.com/slideshowpro/albums/album-16/lg/lig5_on.jpg', zoomImage:'http://brecksargent.com/slideshowpro/albums/album-16/lg/lig5_on.jpg' "> </li>
<!-- ^ here -->
<li><img class = 'cloudzoom-gallery' id="hover2" src ="http://brecksargent.com/slideshowpro/p.php?a=cX12XnxkJXl0bSczJSgwOzIDOjY5OyYzKzE8LTI%2BMiU%2BJzE%2FOicjKD8nNyM%3D&m=1383853420" alt ="Dunno weird though" data-cloudzoom = "useZoom: '.cloudzoom', image:'http://brecksargent.com/slideshowpro/albums/album-16/lg/dod_on.jpg', zoomImage:'http://brecksargent.com/slideshowpro/albums/album-16/lg/dod_on.jpg' "> </li>
<!-- ^ here -->
and so on till the last image.
4) Now the final piece:
$('ul#carousel.elastislide-list img').on('click',function(){
//here we get the updated id (hover1, hover2 etc.)
//and pass it to the cloud-zoomed anchor tag
$new_hoverid = $('img.cloudzoom-gallery-active').attr('id');
$('#imgconstrain a').attr('href','#'+$new_hoverid);
//get the caption of the thumbnail image and set it to the
//p tag with id caption
caption_text = $(this).attr('alt');
var caption_element = document.getElementById('caption');
caption_element.innerHTML = caption_text;
});
//what this code does is, when the cloud-zoomed image is clicked,
//we get the updated href (which is what the above code does)
//and we are going to make that href get clicked so that the fancybox opens
$('#imgconstrain a.open-fancybox').on('click',function(){
$to_open = $(this).attr('href');
$('a.fancybox[href="'+$to_open+'"]').click();
});
});
You can take out this code which was in my previous answer as I have already placed it in the new one:
$(document).ready(function(){
$('#imgconstrain img').on('click',function(){
$new_hoverid = $('img.cloudzoom-gallery-active').attr('id');
$('#1').closest('a').attr('href','#'+$new_hoverid);
});
Full code pastebin
Let me know if it works for you :)
Working on a Greasemonkey script, that will take a certain action if the image loaded on a webpage is a gif or jpg. The code from the page is as follows:
<div id="current_photo">
<div style="text-align:center;">
<img src="[url]/[random numbers].gif/jpg" alt="" style="[styles]">
</div>
</div>
The start of the URL will be unique, as there is only one image on the page with that URL. Need a way to pull that path and get the extension from it.
The HTML in the question is malformed. Is that really an accurate snippet? Link to the target page.
Anyway, code like this should work:
var payloadImage = document.querySelector ("#current_photo div img");
if (/\.gif$/i.test (payloadImage.src) ) {
// DO GIF ACTION HERE
}
else if (/\.jpg$/i.test (payloadImage.src) ) {
// DO JPG ACTION HERE
}
else {
// DO WHATEVER HERE
}
Add id="something" for your image tag. Then something like this:
var path = document.getElementById('something').src;
var extidx = path.lastIndexOf('.');
var extension = path.substr(extidx+1);