JQuery set img src depending on where you click - javascript

I used javascript for loading a picture on my website depending on which "small" photos in ul you clicked...
I had something like that :
<script type="text/javascript">
function viewImage(src, legende) {
document.getElementById("imageBig").src = "images/photos/"+src;
document.getElementById("legend").innerHTML = legende;
}
</script>
and in html simply :
things like that :
<ul id="ulPhotos">
<li>
<a href="#centre" onclick="javascript:viewImage('flute.jpg','La Reine de la Nuit au Comedia')">
<img src="images/photos/carre-09.jpg" alt="" />
</a>
<a href="#centre" onclick="javascript:viewImage('perichole.jpg','Manuelita - <em>La Périchole</em> à l’Opéra Comique')">
<img src="images/photos/carre-03.jpg" alt="" />
</a>
</li>
<li>
<a href="#centre" onclick="javascript:viewImage('12.png','Récital à Carnac, septembre 2008')">
<img src="images/photos/carre-12.jpg" alt="Marion Baglan Carnac Ré" />
</a>
<a href="#centre" onclick="javascript:viewImage('01.jpg','')">
<img src="images/photos/carre-01.jpg" alt="" />
</a>
</li>
</ul>
so you see, I could, depending on which small photos in the unordered list you clicked, load some particular photos, by passing the src string in argument to my viewImage function...
but I decided to use Jquery to get some fade-in effect. But I can't find a way to pass an argument that would tell my JQuery function which photo to load depending on where I clicked...
stuck here :
$(document).ready(function(){
$('#ulPhotos').click(function() {
var newSrc = $('#imageBig').attr("src", "images/photos/11.jpg");
});
});
I don't want the 11.jpg to be hardcoded, I need to pass it through argument when I click on a special li element in my ul element of id #ulPhotos...
I hope I'm clear enough sorry !

karim79 gives a correct solution, but doesn't actually explain your problem.
You are attaching the click handler to the list itself instead of directly to the images. When an attached jQuery behavior callback fires, this is the element that was clicked, which you want to be the a links surrounding the images. In your current case this will be the list itself.
You don't necessarily need to add a class to the thumbnails. $('#ulPhotos a') will get you to them just as easily. I do agree with the suggestion to use a data- attribute on the clickable to know which large image you want to show.
In addition, if you are going to add secondary click behavior to the a elements, you probably want to prevent the default behavior from happening, so something like:
$('#ulPhotos a').click(function (event) {
$('#imageBig').attr('src', $(this).attr('data-big-image'));
event.preventDefault();
});

A pretty straightforward solution would be to assign a common (thumb or whatever) class to all the small images, and store the filename of the bigger images within their rel attributes, e.g.:
<img src="something.jpg" rel="something_big.jpg" class="thumb"/>
<img src="somethingElse.jpg" rel="somethingElse_big.jpg" class="thumb"/>
<img id="bigImage" src="something_big.jpg"/>
$(".thumb").click(function() {
$("#bigImage").attr('src', $(this).attr("rel"));
});
data is another storage mechanism you might consider.
It is also quite common (and simple) to follow a particular convention and 'assemble' the filename of the larger image based on the src of the clicked smaller one, for example:
<img src="something.jpg" class="thumb"/>
<img src="somethingElse.jpg" class="thumb"/>
<img id="bigImage" src="big_something.jpg"/>
$(".thumb").click(function() {
$("#bigImage").attr('src', 'big_' + $(this).attr("src"));
});
That assumes that all of your full-sized images are prefixed with 'big_', so it's a simple matter of appending 'big_' to the src of the clicked thumbnail.

thanks to both of you, my website is working, I give the final code for beginners like me who could have the same needs...
here's the function :
<script type="text/javascript">
$(document).ready(function(){
$('#ulPhotos a').click(function() {
var newSrc= $(this).find('img').attr('src').split("/");
bigPictureName = 'big'+newSrc[2];
$('#imageBig').attr("src", "images/photos/"+bigPictureName).hide();
$('#imageBig').fadeIn('fast');
var alt = $(this).find('img').attr('alt');
$('#legend').html(alt);
});
});
</script>
here are the html elements :
<ul id="ulPhotos">
<li><img src="images/photos/09.jpg" title="La Reine de la Nuit au Comedia" alt="<em>La Reine de la Nuit</em> au Comedia"/>
<img src="images/photos/03.jpg" title="Manuelita, La Périchole à l’Opéra Comique" alt="Manuelita, <em>La Périchole</em> à l’Opéra Comique" /></li>
<li><a href="#centre" ><img src="images/photos/12.png" title="" alt="Marion Baglan Carnac Ré" /></a>
I used the alt attribute to append the legends so as to be able to add some html tags like <em > because the title appears when you hover your mouse on the thumbnails, and I didn't want people to see strange tags for them...
sometimes, it's a little slow when you click very fast it can stay on the previous photo for a little while at first try, maybe because I didn't use a CDN to put the minified version of jquery (I read such an advice), don't know, I'm truly a beginner, but it's nothing serious anyway...
by the way, the page is here..http://www.marion-baglan.net/photos.htm

Related

Reducing .parent and .children calls to get to desired parameter

I have an eCommerce page of products with some small thumbnails below. When I mouse moused over a thumbnail I want to swap the different variation image into the product image. I have this working using the code below but I assume this isn't the best way to do this? Can anyone suggest a better way for me to grab the "product-image" src= tag and update it? The number of parent / child calls I've used to set the right data seems excessive.
Thanks in advance. Tim
<script>
$(document).ready(function(){
$('.nSwatchProduct').hover(function(){
var newSource = $(this).attr('data-variation-image');
$(this).parent('._itmspec_listitm').parent('.nColourSwatch').parent('.categoryswatch').parent('.caption').parent('.thumbnail').children('.thumbnail-image').children('.product-image').attr('src', newSource);
});
});
</script>
web page hierarchy
<div class="thumbnail">
<a href="https://www.website.com/productpage" class="thumbnail-image">
<img src="/assets/thumbL/imagename.jpg" itemprop="image" class="product-image" alt="" rel="itm">
</a>
<div class="caption">
<div class="nColourList categoryswatch">
<a class="_itmspec_lnk thumbnail nColourSwatch" href="https://www.website.com/productpage" ref="1_83" data-toggle="tooltip" data-placement="top" title="" data-original-title="Blue">
<div class="_itmspec_listitm" ref="1_83">
<img class="nSwatchProduct" src="/assets/thumb/variationimage.jpg" alt="Blue" data-variation-image="/assets/thumb/variationimage.jpg">
</div>
</a>
Use .closest to select nearest common parent and then .find that element you need
$(this).closest('.thumbnail').find('.thumbnail-image .product-image')

How should I not load the images with broken link?

I'm working on a feature, in which images are being rendered from the servers. I was working on aligning the images but found that there is a lot of white space. This was the reason, due to loading of images with a broken link.
HTML :
<div class="image-result" *ngIf="Display('images')">
<div class="col-sm-3" *ngFor="let item of items$|async">
<a href="{{item.link}}">
<figure>
<img class="res-img" src="{{item.link}}" onerror="this.style.display='none'">
</figure>
</a>
</div>
</div>
I have used onerror="this.style.display='none'" to solve the problem, but leaves a lot of white space when images are being loaded from the server. Is there any solution for it like to remove img tag whenever a image with a broken link has been detected ? I have gone through stackoverflow before asking question, but I'm not able to solve this problem. It would be great if someone can help me out. Thanks! :)
Instead of onerror="this.style.display='none'" to hide an image, you can use onerror="this.parentNode.removeChild(this)" to remove the image tag altogether.
If you want to remove the entire column, in your specific case you can do the following.
var colEl = this.parentNode.parentNode.parentNode;
colEl.parentNode.removeChild(colEl);
Or, in your HTML:
onerror="this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode)"
You should probably move that to some JavaScript function and attach your handler by saying
element.addEventListener('error', function() { /* ... */ });
References: parentNode, removeChild, addEventListener.
If you don't care about supporting Internet Explorer, you can also use remove instead of doing the parentNode.removeChild trickery. That would be particularly useful for reducing the code length in your onerror attribute, would you choose to use it, but I don't recommend that.
A more angular-way of doing this would be:
<img src="{{item.link}}" (error)="item.brokenImage=true">
So you would have:
<div class="col-sm-3" *ngFor="let item of items$|async">
<div *ngIf="!item.brokenImage">
<a href="{{item.link}}">
<figure>
<img class="res-img" [src]="item.link" (error)="item.brokenImage=true">
</figure>
</a>
</div>
</div>
You need to listen for the error event of the image element, and assign a boolean on whether the image loaded successfully or not. Then, depending on that value angular will either show the image with the div, or remove it from the DOM.

Google Tag Manager - CSS selector challenge

I am trying to get the URL of a link in the source code. The challenge is that the URL is hidden behind a image, and thus only letting me fetch the image-url.
I've been trying to figure a way to solve this issue by using the new CSS selector in the trigger system and also made a DOM variable that should get the URL when the image is clicked. There can also be multiple downloads.
Here is an example of what I am trying to achieve:
<div>
<div class="download">
<a href="example.com/The-URL-I-Want-to-get-if-top-image-is-clicked.pdf" target="_blank">
<img src="some-download-image.png"/></a>
<div class="download">
<a href="example.com/Another-URL-I-Want-to-get-if-middle-image-is-clicked.pdf" target="_blank">
<img src="some-download-image.png"/></a>
<div class="download">
<a href="example.com/Last-URL-I-Want-to-get-if-bottom-image-is-clicked.pdf" target="_blank">
<img src="some-download-image.png"/></a>
</div>
</div>
There are much code above and below this snippet, but with the selector it should be fairly easy to get the information I want. Only that I don't.
If anyone have met this wall and solved it, I really would like to know how. :)
This is one possible solution. So as I understand it, you would like to grab the anchor element's href attribute when you click the "download" image.
A Custom Javascript variable would need to be created so that you can manipulate the click element object:
function(){
var ec = {{Click Element}};
var href = $(ec).closest('a').attr('href');
return href;
}
So you will need to do your due diligence and add in your error checking and stuff, but basically this should return to you the href, and then you will need to parse the string to extract the portion that you need.

No image displayed in Fancybox

I am having trouble getting fancybox to display its corresponding images on a website that I'm building http://www.nomadicdrift.com/test/kaniwa#events . It's a custom one page portfolio theme that I set up on the WordPress platform.
If you follow the link to the events section you will see 1 figure item in a gallery like position. I have this image set up to work as a fancybox gallery, but when you click on it, it opens up the fancybox interface but does not place a image in the frame, even though it should. So this is the problem...the images do not show up in fancybox and instead I see just the frame.
Here is the html that I'm displaying:
<figure>
<a class="fancybox" data-fancybox-type="Fashion Show de Paris, France" href="http://www.nomadicdrift.com/test/kaniwa/wp-content/uploads/2012/07/NM2.jpg">
<img class="attachment-evento wp-post-image" width="231" height="191" title="NM" alt="NM" src="http://www.nomadicdrift.com/test/kaniwa/wp-content/uploads/2012/07/NM2-231x191.jpg">
</a>
<figcaption>
<a class="fancybox" data-fancybox-type="Fashion Show de Paris, France" href="http://www.nomadicdrift.com/test/kaniwa/wp-content/uploads/2012/07/CEDESAN.jpg"> </a>
<h4>Fashion Show de Paris, France</h4>
</figcaption>
</figure>
I'm not going to bore you with the PHP that I used to get that output because I think the problem lies elsewhere.
***I have tried to set up a simple standard fancybox gallery on the site also, but it gives me thes same problem, leading me to believe that the problem is deeper than the html markup. I have also successfully used this same markup for a one thumbnail fancybox gallery on another site.
I thought maybe it was due to some conflict in the .js files I'm using. I tried uninstalling all of my plugins/addons (which aren't too many) one by one and still had the same result. I have all of my personal javascript in the functions.js file, which is where I call the fancybox plugin using the standard $("a.fancybox").fancybox();.
I have installed this plugin before on other sites and have searched extensively for an answer, so any help is greatly appreciated.
Thanks,
Sean
Well, your code may seem semantically correct for a fancybox but is not. The problem that you have is that fancybox uses the data-fancybox-type attribute to determine what type of content it should open (in your case is an image gallery) BUT "Fashion Show de Paris, France" doesn't say anything to fancybox so the type of content is unknown or undefined hence the empty box.
The valid options for that attribute should be either image, iframe, ajax, html or inline.
Maybe you meant to use data-fancybox-group="gallery_name_here". Check https://stackoverflow.com/a/9037826/1055987 for more.
You may try to remove the data-fancybox-type attribute (reserved for fancybox) -OR- rename it in something like
data-description="Fashion Show de Paris, France"
... for your own use, so it won't conflict with fancybox.
BTW, another issue that you have is that the z-index of you header (#header) is higher (9998) than the fancybox z-index (which is around 8010 by default) so I would recommend you to lower the z-index of your #header, otherwise the fancybox close button will be placed behind of it.
Saludos a la tierra del buen café.
Can you try
<figure>
<a class="fancybox" data-fancybox-type="Fashion Show de Paris, France" href="http://www.nomadicdrift.com/test/kaniwa/wp-content/uploads/2012/07/NM2.jpg">
<img class="attachment-evento wp-post-image" width="231" height="191" title="NM" alt="NM" src="http://www.nomadicdrift.com/test/kaniwa/wp-content/uploads/2012/07/NM2-231x191.jpg">
</a>
<figcaption>
<h4>Fashion Show de Paris, France</h4>
</figcaption>
</figure>
Should only leave one <a class="fancybox"/>
Remove the orphaned:
<a class="fancybox" data-fancybox-type="Fashion Show de Paris, France" href="http://www.nomadicdrift.com/test/kaniwa/wp-content/uploads/2012/07/CEDESAN.jpg"> </a>

cant find my error in my html code, for a javascript quiz

I have placed my website in my dropbox so you can see my problem. What I am trying to do is, when you click the image next to tennis or squash it turns red (false.png) and when they click badminton it turns green (true.png), which then makes the next question appear. At the moment only the next question appears and I'm having trouble with the image changing.
http://dl.dropbox.com/u/13722201/website/quiz.html
Please could you poke around in the source code and figure it out because I'm baffled.
<a onclick="document.getElementById('badminton-answer').setAttribute('src', 'images/true.png'" href="javascript:toggle();">
<img id="badminton-answer" border="0" alt="" src="images/answer.png" width="290" height="60"/>
</a>
the javascript showing/ hiding div id="next"
<script language="javascript">
function toggle() {
var ele = document.getElementById("next");
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
Your onclick handlers contain this code:
document.answer.src='images/false.png'
document doesn't have an answer property. The best way to manipulate the DOM in JavaScript is to assign your HTML element a unique ID:
<img id="tennis-answer" alt="" src="images/answer.png" width="290" height="60"/>
If an element has a unique ID, then you can get a reference to it and modify the element:
document.getElementById('tennis-answer')
.setAttribute('src', 'images/false.png');
Here's how it all looks together for the Badminton answer:
<a onclick="document.getElementById('badminton-answer').setAttribute('src', 'images/true.png'" href="javascript:toggle();">
<img id="badminton-answer" border="0" alt="" src="images/answer.png" width="290" height="60"/>
</a>
All three images have the same id (answer). They should probably have unique IDs. Also, I'd put the image flipping code into a function and call the function on click instead of putting the code in the onclick of the button.

Categories

Resources