how to pass image for popup into jquery without hard coding - javascript

I'm learning jQuery and I need to figure out how to not hard-code. So I have 2 different divs (master and popup) being populated by an array. The first div (master) is visible and the second (popup) that I'm using as a pop-up is hidden. On the view, you see an image in the div( master) and when it is clicked, I have a jQuery function that triggers the hidden div (popup) to show up.
Now if 10 items are gotten from the array, I have 10 images displaying but when I click on any image (including the first), only the first image in the array populates the popup div.
I hard-coded a 'fix' based on my current jQuery knowledge but this is repetitive code which means I can only have the amount of divs declared in my jQuery. I need to find a way that each image displays it's corresponding popup without having to hard code it in all the way
My html code:
Master div:
<div class="master">
<div id="imgprop"><img src="IMGCOMP/bgggg.jpg" alt="Gallery Image" height="238" width="238" /></div>
<div id="ps1" class="popit1" #hard coded popit id>
<section>
<span>IMAGE TITLE</span>
<span id="zoom"></span>
</section>
</div>
</div>
<div class="master">
<div id="imgprop"><img src="IMGCOMP/bgg.jpg" alt="Gallery Image" height="238" width="238" /></div>
<div id="ps1" class="popit2" #hard coded popit id>
<section>
<span>IMAGE TITLE</span>
<span id="zoom"></span>
</section>
</div>
</div>
Popup div:
<div id="GbgPopup1" #hard coded gbpopup id>
<div id="GPopupcontent">
<div class="closeit"></div>
<span class="ecs_tooltip_">Press esc to close <span class="arrow"></span></span>
<div class="image">
<img src="IMGCOMP/bgggg.jpg" alt="Gallery Image" height="400" width="430" />
</div>
</div>
</div>
<div id="GbgPopup2" #hard coded gbpopup id>
<div id="GPopupcontent">
<div class="closeit"></div>
<span class="ecs_tooltip_">Press esc to close <span class="arrow"></span></span>
<div class="image">
<img src="IMGCOMP/bgg.jpg" alt="Gallery Image" height="400" width="430" />
</div>
</div>
</div>
My jQuery code:
jQuery(function($) {
#hard coded
$(".popit1").click(function() {
setTimeout(function(){ // then show popup, deley in .5 second
loadPopup1(); // function show popup
}); // .5 second
return false;
});
$(".popit2").click(function() {
setTimeout(function(){ // then show popup, deley in .5 second
loadPopup2(); // function show popup
}); // .5 second
return false;
});
/* event for close the popup */
$("div.closeit").hover(
function() {
$('span.ecs_tooltip_').show();
},
function () {
$('span.ecs_tooltip_').hide();
}
);
$("div.closeit").click(function() {
disablePopup(); // function close pop up
});
$(this).keyup(function(event) {
if (event.which == 27) { // 27 is 'Ecs' in the keyboard
disablePopup(); // function close pop up
}
});
var popupStatus = 0; // set value
#hard coded
function loadPopup1() {
if(popupStatus == 0) { // if value is 0, show popup
$("#GbgPopup1").fadeIn(0500); // fadein popup div
popupStatus = 1; // and set value to 1
}
}
function loadPopup2() {
if(popupStatus == 0) { // if value is 0, show popup
$("#GbgPopup2").fadeIn(0500); // fadein popup div
popupStatus = 1; // and set value to 1
}
}
#hard coded
function disablePopup() {
if(popupStatus == 1) { // if value is 1, close popup
$("#GbgPopup1").fadeOut("normal");
$("#GbgPopup2").fadeOut("normal");
popupStatus = 0; // and set value to 0
}
}
});
Every help and more jQuery resources to help improve my knowledge is welcomed

I hope I understand your question right. Do you want to know how to take the picture source from master and put it into the popup?
To get the src of the picture in master you can do this:
$(".popit").click(function() {
setTimeout(function(){ // then show popup, deley in .5 second
loadPopup(this); // function show popup
}); // .5 second
return false;
});
function loadPopup(clickedElement) {
if(popupStatus == 0) { // if value is 0, show popup
// first find the img tag from master
var imgSrc = $(clickedElement).parent().find("img").attr("src");
var popup = $("#GbgPopup");
popup.find("img").attr("src", imgSrc);
popup.fadeIn(0500); // fadein popup div
popupStatus = 1; // and set value to 1
}
}
I'm sorry if there are bugs in the code, I did not run it. I trust you can remove the hard coded part from your code again.

create a master div and use http://api.jquery.com/appendto/ to dinamically generate every popup passing only the image and the counter
ie:
function generatePop(image, counter) {
var html = '<div class="ecs_tooltip_" id="pop"'+counter+"><img src=... </div>';
$(html).appendTo('#master-div');
}

After seeing Martin's answer, I was able to dig more into jQuery and adapt his answer to make it work.
All I did was move the code in loadpopup() function into the parent .click() function, change the $(".popit").click for the div(master) to $(".master").click to effectively select the whole div, used the $(this) so I can get the current clicked img in the master div and then replaced the src in the popup div
var popupStatus = 0; // set value
$(".master").click(function() {
var imgSrc = $(this).find('img').attr('src');
var popup = $("#GbgPopup");
popup.find("img").attr("src", imgSrc);
popup.fadeIn(0500); // fadein popup div
popupStatus = 1; // and set value to 1
//return false;
});

Related

How to tell if <img> has href attribute?

So I have a simple slideshow using JavaScript to fade images in and out, where all but one of the img elements do not have a href attribute. I would like to put the href attribute of the image into the href attribute of the caption (actually the img alt attribute) so that the text is clickable when the particular slide shows up, and becomes unclickable when the slide goes to the next one. I am very inexperienced in JS and cannot find any resources online to help me with this particular issue. Here is the part of my HTML file (called Finley.html) that is used, and my slideshow.js file.
<section>
<!-- Slideshow -->
<h2 id="caption">Car ride home! First time meeting each other.</h2>
<img id="slide" src="images/Finley/car_ride_home.jpg" alt="">
<div id="slides">
<img src="images/Finley/car_ride_home.jpg" alt="Car ride home! First time meeting each other.">
<img src="images/Finley/he_lay.jpg" alt="Handsome boy!">
<img src="images/Finley/awwww.jpg" alt="First photo together">
<img src="images/Finley/photogenic_af.jpg" alt="Papa, we made it to the community Instagram!" href="https://google.com" target="_blank">
<img src="images/Finley/first_vet.jpg" alt="First vet trip was successful">
<img src="images/Finley/blop.jpg" alt="blop.">
<img src="images/Finley/squishy_cheek.jpg" alt="Car rides make me sleepy">
<img src="images/Finley/first_beach.jpg" alt="First time at the beach and I got rocked by the waves">
<img src="images/Finley/sploot.jpg" alt="sploot.">
<img src="images/Finley/floopy_ears.jpg" alt="My family loves how floopy my ears are!">
<img src="images/Finley/daisy_gf.jpg" alt="Playing with my friend Daisy!">
</div>
</section>
slideshow.js:
$(document).ready(function() {
//declare variables
var nextSlide = $("#slides img:first-child");
var nextCaption;
var nextSlideSource;
// the function for running the slide show
var runSlideShow = function() {
// write the function
$("#caption").fadeOut(1000);
$("#slide").fadeOut(1000,
function() { //callback function
if (nextSlide.next().length == 0) {
nextSlide = $("#slides img:first-child");
} else {
nextSlide = nextSlide.next();
}
nextSlideSource = nextSlide.attr("src");
nextCaption = nextSlide.attr("alt");
if (nextCaption == "Papa, we made it to the community Instagram!") {
$("#caption").attr("href", nextSlide.attr("href"); $("#caption").attr("target", nextSlide.attr("target");
}
$("#slide").attr("src", nextSlideSource).fadeIn(1000); $("#caption").text(nextCaption).fadeIn(1000);
}
); //callback
}; //ready
// start slide show
var timer1 = setInterval(runSlideShow, 5000);
// here's one way to code this app without using the toggle event method
$("#slide").click(function() {
if (timer1 != null) {
clearInterval(timer1);
timer1 = null;
} else {
timer1 = setInterval(runSlideShow, 1000);
}
});
})
This code displays the caption as text above the image, and the image stays on screen for 5 seconds before fading to the next image. To clarify, I'd like the caption text that appears to become a hyperlink to Google (actual site censored) for the one picture when it is displayed, and then return to normal once the next picture comes up. I tried putting line 21-24 in to test for the caption and set the attribute, but those lines stop the slideshow from working (remove those lines to see how it should behave). Maybe it's something in the if statement in line 21, but I'm not sure how to proceed. Any help or tips would be appreciated!
You can do it either like this:
this.hasAttribute('href');
or
$(this).is('[href]');
More Info

How to determine the selected element while using multiple selectors in jQuery?

I am writing a simple fade-slideshow with a two next and previous buttons.
(Using semantic-ui's buttons)
<div id="slides_container">
<div id="slide0" class="slide_image"><img src="images/slide0.png" alt=""></div>
<div id="slide1" class="slide_image"><img src="images/slide1.png" alt=""></div>
...
</div>
<div id="slides_counter_container">
<div class=" ... transition_button" id="previous_button">...</div>
<div id="slides_counter"></div>
<div class=" ... transition_button" id="next_button">...</div>
</div>
I want to handle both cases of pressing next or previous button in one jQuery click-event.
$(".transition_button").click(function (){
...
$("#slide"+current_slide).fadeOut(FADE_DURATION, function () {
var temp = $(this).attr("id");
if (temp == "next_button"){
...
// current_slide ++
}
else{
...
// current_slide --
}
// fadeIn() new current_slide
});
});
By using $(this).attr("id") I will get one of these id s: slide0 or slide1 or ... (depending on the current slide number, which isn't related to the next or previous buttons at all!
What's the problem?
How can we specifically find the div button anchor, etc, which caused a multiple selector event, to be fired?
what is the problem?
you are getting id inside fadeOut callback function here right now $(this) is reffers to .slide_image which is slider div element not the clicked element
$(".transition_button").click(function (){
//move temp here
var temp = $(this).attr("id");
$("#slide"+current_slide).fadeOut(FADE_DURATION, function () {
if (temp == "next_button"){
...
// current_slide ++
}
else{
...
// current_slide --
}
// fadeIn() new current_slide
});
});

Show div only if specific other divs have been clicked

I am new to jQuery (this is my second attempt). I looked for answers via Google and StackOverflow and I have tried quite a few but have yet to figure out the last part of my problem. Any help or guidance is most appreciated.
What I want to do is have a bunch of images(apple, pumpkin, candle, etc) that when clicked, fade the image out and then cross off the image's name in a text list. Then, if you click on specific sets of those images they will show a div containing a deal.
An example: If you click on the images of apple, pear and pumpkin (in any order) a deal will show.
Another example: You click on the images of candle, apple, pumpkin and key(in any order) a deal will show.
Another example: You click on all image items(in any order) a deal shows.
I have the first part working (click on an image, it fades out and crosses its name off the list).
What I need help with is checking to see if certain combinations of images have been clicked and if so show the deal div.
I was thinking I could use index for this but I haven't been able to make it work. Maybe there is a better way? Thanks for any guidance.
Here is my test code so far (JSFIDDLE):
HTML
<div class="pic1">
<img width="50" height="50" src="http://us.123rf.com/400wm/400/400/chudtsankov/chudtsankov1208/chudtsankov120800002/14670247-cartoon-red-apple.jpg" />
</div>
</div>
<div class="pic2">
<img width="50" height="50" src="http://www.in.gov/visitindiana/blog/wp-content/uploads/2009/09/pumpkin.gif" />
</div>
<div class="pic3">
<img width="50" height="50" src="http://upload.wikimedia.org/wikipedia/commons/f/fc/Candle_icon.png" />
</div>
<div class="pic4">
<img width="50" height="50" src="http://tasty-dishes.com/data_images/encyclopedia/pear/pear-06.jpg" />
</div>
<div class="pic5">
<img width="50" height="50" src="http://free.clipartof.com/57-Free-Cartoon-Gray-Field-Mouse-Clipart-Illustration.jpg" />
</div>
<div class="pic6">
<img width="50" height="50" src="http://images.wisegeek.com/brass-key.jpg" />
</div>
<div id="items">
<p class="apple">Apple</p>
<p class="pumpkin">Pumpkin</p>
<p class="candle">Candle</p>
<p class="pear">Pear</p>
<p class="mouse">Mouse</p>
<p class="key">Key</p>
</div>
<div class="someText">Reveal Deal #1 after finding apple, candle and mouse</div>
<div class="deal1">This is deal box #1! You must have found apple, candle and mouse! WIN</div>
<div class="someText">Reveal Deal #2 after finding key, pumpkin, pear and mouse!</div>
<div class="deal2">This is deal box #2! You must have found key, pumpkin, pear and mouse!</div>
<div class="someText">Reveal Deal #3 after finding ALL objects!</div>
<div class="deal3">This is deal box #3! You must have ALL the items!</div>
<div id="output"></div>`
CSS
.intro, .someText {
color:#333;
font-size:16px;
font-weight: bold;
}
.deal1, .deal2, .deal3 {
font-size: 18px;
color: red;
}
Javascript: jQuery
$(document).ready(function () {
$('.deal1, .deal2, .deal3').hide();
$('.pic1').click(function () {
$(this).data('clicked');
$('#items p.apple').wrap('<strike>');
$(".pic1").fadeOut("slow");
});
$('.pic2').click(function () {
$(this).data('clicked');
$("#items p.pumpkin").wrap("<strike>");
$(".pic2").fadeOut("slow");
});
$('.pic3').click(function () {
$(this).data('clicked');
$("#items p.candle").wrap("<strike>");
$(".pic3").fadeOut("slow");
});
$('.pic4').click(function () {
$(this).data('clicked');
$("#items p.pear").wrap("<strike>");
$(".pic4").fadeOut("slow");
});
$('.pic5').click(function () {
$(this).data('clicked');
$("#items p.mouse").wrap("<strike>");
$(".pic5").fadeOut("slow");
});
$('.pic6').click(function () {
$(this).data('clicked');
$("#items p.key").wrap("<strike>");
$(".pic6").fadeOut("slow");
});
$(document).on('click', '*', function (e) {
e.stopPropagation();
var tag = this.tagName;
var index = $(tag).index(this); // doesn't work, as it gives the total no. elements
$('#output').html(index);
});
});
first of all you can give your divs a corresponding data value to their p items for instance if you implement your div ( and all the other divs)
<div class="pic" data="pumpkin">
instead of
<div class="pic2">
You can write an almost oneliner with jquery
$('.pic').click(function () {
$("#items p."+$(this).attr("data")).wrap("<strike>");
$(this).fadeOut("slow");
});
you can define your sets:
set1 = ["apple","pumpkin"]
and after every click you can check clicked paragraphes with
$(document).ready(function () {
var set1 = ["apple", "candle", "mouse"]
$('.deal1, .deal2, .deal3').hide();
$('.pic').click(function () {
$("#items p." + $(this).attr("data")).wrap("<strike>").addClass("strike");
$(this).fadeOut("slow");
//test for set1
set1Completed = true;
for (i = 0; i < set1.length; i++) {
if ($("p.strike." + set1[i]).length==0) {
set1Completed = false;
break;
}
}
if (set1Completed) {
$('div.deal1').fadeIn(); // or fadeIn whatever u want
}
});
Create a custom event:
$('.HiddenItem').css({display:'none'}).on('somethingElseClicked',function(){
$(this).show();
});
And then trigger it with the other click:
$('.ItemToTrigger').on('click',function(e){
$('.HiddenItem').trigger('somethingElseClicked');
});
This is obviously supergeneralized, but it gives the framework necessary to trigger the event you want.
EDIT
Alright, so you will need to store each value for the clicks needed, as well as the total needed. I always prefer to use object-based variables rather than globals, so:
var click = {
deal1:[0,2],
deal2:[0,3],
deal3:[0,5]
}
This creates arrays for each deal, the first being the number of clicks that have happened and the second being the total needed minus 1. You will then increment the "clicks that have happened" value, as well as prevent it from allowing double-clicks, by the JS described later. First, I recommend adding a generic class to all clickable items, as well as the deal items they are associated with, and verifying that way. The HTML:
<div class="picItem d1" data-fruit="apple">
<div class="picItem d2" data-fruit="pumpkin">
<div class="picItem d1" data-fruit="candle">
<div class="picItem d2" data-fruit="pear">
<div class="picItem d1 d2" data-fruit="mouse">
<div class="picItem d2" data-fruit="key">
And the JS I described:
$('.picItem').on('click',function(){
var $this = $(this),
$fruit = $this.data('fruit');
$this.fadeOut('slow');
if($this.hasClass('d1') && !$this.hasClass('clicked1')){
if(click.deal1[0] < click.deal1[1]){
click.deal1[0]++;
$this.addClass('clicked1');
} else {
$('.deal1').trigger('showDeal');
}
}
if($this.hasClass('d2') && !$this.hasClass('clicked2')){
if(click.deal2[0] < click.deal2[1]){
click.deal2[0]++;
$this.addClass('clicked2');
} else {
$('.deal2').trigger('showDeal');
}
}
if(!$this.hasClass('clicked3')){
if(click.deal3[0] < click.deal3[1]){
click.deal3[0]++;
$this.addClass('clicked3');
} else {
$('.deal3').trigger('showDeal');
}
}
$('.'+$fruit).wrap("<strike>");
});
The last if is for all elements clicked, hence not the need for adding a class and checking. The final piece grabs the associated data attribute and strikes it out.
Now you just trigger the event:
$('.deal1,.deal2,.deal3').on('showDeal',function(){
$(this).show();
});
This event will only be triggered when the appropriate number of clicks has been reached. Here is the jsFiddle you gave me updated to show it is working as requested.
If you want to only allow one deal, you would just turn off the event after being triggered:
var $allDeals = $('.deal1,.deal2,.deal3');
$allDeals.on('showDeal',function(){
$(this).show();
if($(this).hasClass('deal3')){
// this is to prevent deal 1 and deal 2 showing, since the criteria for them is also met
$allDeals.not('.deal3').hide();
}
// this turns off all other deals
$allDeals.off('showDeal');
$('.picItem').off('click');
});
Not sure if you would need it or not, figured I would include it just in case. Here is an updated jsFiddle to show that case working.

jquery animations happen randomly

I have a kind of splash screen, where you press one of the logo's and it animates the logo to the center, then loads the content for it. Then when you press the main top logo, it hides the content and goes back to the splash screen. However I am having problems with this.
Such as, the container hides, then comes back.
Look for yourself: http://dan.roguedraco.net/SpyroDev/
If happens if you click the top logo before the content has fully appeared, but I want to allow for all these occurences. Because it is possible a user may do the same.
Javascript:
$(document).ready(function() {
var inPage = false;
$('.ajax-loader').click(function() {
if(inPage == false) {
inPage = true;
var Obj = this;
$(Obj).siblings("a").fadeOut(500,function() {
if($(Obj).hasClass('left') || $(Obj).hasClass('right')) {
$(Obj).animate({left:'300px'},'slow','easeOutBack',function() {
$('#pageContent').fadeIn(500,function() {
$("#tabs").tab();
});
});
}
else {
$('#pageContent').fadeIn(500,function() {
$("#tabs").tab();
});
}
$(Obj).addClass('current-project');
});
}
});
$('#rootLogo').click(function() {
var Obj = $('.current-project');
if(inPage == true) {
inPage = false;
$('#pageContent').fadeOut(500,function() {
$(this).hide();
if($(Obj).hasClass('left')) {
$(Obj).animate({left:'0px'},'slow','easeOutBack',function() {
$(Obj).siblings("a").fadeIn(500);
});
}
else if($(Obj).hasClass('right')) {
$(Obj).animate({left: '600px'},'slow','easeOutBack',function() {
$(Obj).siblings("a").fadeIn(500);
});
}
else {
$(Obj).siblings("a").fadeIn(500);
}
$(Obj).removeClass('current-project');
});
}
});
});
Html:
<div id="thumbnails">
<div class="row-fluid">
<div class="span12" style="text-align: center;color:#fafafa;">
Click a plugin title for more information and downloads.
</div>
</div>
<div class="row-fluid">
<div class="span12" id='thumbnails'>
<img src="projects/JumpPorts/thumb.png" alt="JumpPorts" />
<img src="projects/RankUpOnKills/thumb.png" alt="RankUpOnKills" />
<img src="projects/InfoButton/thumb.png" alt="InfoButton" />
</div>
</div>
</div>
<div id="pageContent" style="display:none;">
<div class="row-fluid">
...
.stop()
have you tried to use .stop() before your .animate() and .fadeIn() and other animate methods? like: $(Obj).stop().animate({left:
Have you consider to not make the "" of the logo itself clickable? I mean, you're making your event ready whenever it's clicked.
Try this:
In the event of .ajaxloader add on the logo image a sorrounding it at the end of the code of the event.
Then you switch:
$('#rootLogo').click(function() {
var Obj = $('.current-project');
....
}
for this:
$('#click-event').click(function() {
// Assuming #click-event is the name of the span you placed
var Obj = $('.current-project');
.....
}
and in the end you delete the span created on the .ajaxloader.click event
It's an idea, you can use it, tell me if it worked

Make image SlideShow and text by jQuery

I want make a jquery slideshow with show text(each text in title tag <img>) in following image without use plugin, i tried as: (it doesn't work [i should use of class div.mediumCell for tag img and text it])
DEMO: http://jsfiddle.net/pzyxk/
$('.fadein .mediumCell:not(:first)').hide();
setInterval(showNext, 3000);
function showNext() {
$('div#caption').remove();
var current = $('.fadein :first-child');
var next = current.next('.mediumCell');
current.fadeOut("slow", function () {
$(this).appendTo('.fadein');
})
caption(next);
$(next).next(".mediumCell").andSelf().fadeIn()
};
function caption(element) {
$('<div class="mediumCell"/>').hide().html($(element).attr("alt")).insertAfter($(element)).fadeIn();
};
How is fix it?
For you html are:
<div class="presentaion">
<span class="caption"></span>
<img src="http://www.ct4me.net/images/Showing_Grade_1.jpg" width="100px" title="MyTitle_1" />
<img src="http://www.ct4me.net/images/dmbtest.gif" width="100px" title="MyTitle_2" />
<img src="http://celticevolution.com/images/test-201.gif" width="100px" title="MyTitle_3" />
</div>
And JS are:
show($('div.presentaion img:first')); // show first slide
function show(el) {
el.parents('div.presentaion').find('img').hide(); // hide all slide
el.prev('span.caption:first').html(el.attr('title')); // show caption from title
el.show(); // show image
setTimeout(function() {
if (typeof(el.next('img:first')) != 'undefined') {
show(el.next('img:first')); // set timeout to show next
}
}, 3000);
}
Edited here, jsfiddle

Categories

Resources