1

I'm trying to fade images in and out instead of them instantly changing (as they currently do).

See my codepen for a working example: http://codepen.io/jsegarra/pen/ExCrj If you press a number the image will change.

I have a dynamic page and when someone gets to the projects section of the page there are 48 different projects to view. The codepen is an example of what one of those projects might look like. I know the inline onclick function is probably not the best way to do this, but every jQuery function i have attempted(many) have not worked correctly.

I would love one jQuery function that would control the changing of the image across all 48 sections, as I have jQuery controlling most of the page. I originally set up the HTML this way, which works, but the images change instantly, I need them to fade in/out.

I've tried a number of things, including just adding .fadeIn()/Out() somewhere in that inline function.

Then I took out the src of those images from the li and created new divs inside the encompassing div:

<div class="nextImage secondImage">
    <img src="document.getElementById('br_img').src = 'http://kerlabs.net/wp-content/uploads/2014/03/Scenic-Waterfall-HD-Wallpaper.jpg'" />
</div>

etc. for all 4 and added display: none; for those in the CSS to go with this jQuery function and added display:

$(document).ready(function () {
$('.one').click(function () {
    $('.shownImage').fadeOut(300, function () {
        $('.firstImage').fadeIn(500);
    });
});
$('.two').click(function () {
    $('.shownImage').fadeOut(300, function () {
        $('.secondImage').fadeIn(500);
    });
});
$('.three').click(function () {
    $('.shownImage').fadeOut(300, function () {
        $('.thirdImage').fadeIn(500);
    });
});
$('.four').click(function () {
    $('.shownImage').fadeOut(300, function () {
        $('.fourthImage').fadeIn(500);
    });
});
});

That didn't do anything, and neither did the 20 variations of it that I've tried. I'm basically stuck and need inspiration and help. I might look into CSS3 animations also to get this to work, because the HTML works, just needs little effect. Thanks for any help!

Stan
  • 62
  • 1
  • 8

3 Answers3

0

here you go: http://codepen.io/anon/pen/ltosw

you just need to give each of your lis a unique id and do this code on click event of them:

$('#one').click(function(){
    $('#br_img').fadeOut(300,function(){        
      $('#br_img').attr('src','http://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Cathedral_Group_panorama_from_Cathedral_Group_Scenic_Turnout2.JPG/800px-Cathedral_Group_panorama_from_Cathedral_Group_Scenic_Turnout2.JPG');
      $('#br_img').fadeIn(300);
    });
  });

just FYI, the links to your second and third pictures seem to be broken!

UPDATE:

this is how you can do it with storing the links of the images into a data-attribute: http://codepen.io/anon/pen/niKzs

$('.imgNumerals li').click(function(){
    var that=this;
    $('#br_img').fadeOut(300,function(){        
      $('#br_img').attr('src',$(that).data('image'));
      $('#br_img').fadeIn(300);
    });
  });
Amin Jafari
  • 7,157
  • 2
  • 18
  • 43
  • Thanks, but I was trying to stick with classes as I have a bunch of these sections. That works nicely, but I would have to make 48 different functions this way, and I was trying to avoid that. – Stan Jul 16 '14 at 20:11
  • you could use classes but you need to change the way of naming your images, for example you could name them as numbers (e.g. 1.jpg, 2.jpg, etc). if such change is possible for you, let me know to update the answer. – Amin Jafari Jul 16 '14 at 20:21
  • Those images were just to show an example. The actual images have their file path and then the Project name and a number like you say. blackStoneRiverValley/1.jpg is an example, so for that project there is 1.jpg, 2.jpg, 3.jpg, and 4.jpg and then the next project would be projectX/1.jpg and so on. Would that work with what your thinking? Or do you mean 1.jpg through to 192.jpg? (4 images * 48 projects = 192 images). – Stan Jul 16 '14 at 20:33
  • if you want to have the images in different directories for each project, then you have to repeat the code for each project, else you have to have them all in one directory (location), would that be ok? – Amin Jafari Jul 16 '14 at 20:36
  • or another way would be to set all images links in your html if that's not too difficult to do for you, choose the way and let me know – Amin Jafari Jul 16 '14 at 20:37
  • I'd rather keep them seperate, I could set all image link in the html, shouldn't be too hard – Stan Jul 16 '14 at 20:41
0

Use the data-attribute HTML attribute. You can store an image link in there. JSFIDDLE

<li class="swap" data-img="http://image-link.jpg">1</li>

var object;
$('.swap').click(function(){
    object = $(this);
    $('#br_img').fadeOut(300, function(){ 
      $('#br_img').attr("src",object.attr("data-img")).fadeIn(300); 
    });
});
// this one jQuery function would set up the elements for all 48 of your 
// portfolio items (no need to duplicate it 48 times) as long as the image 
// URLs are stored in the data-img HTML attributes
JRulle
  • 7,448
  • 6
  • 39
  • 61
  • That's interesting. I will test that out and let you know! Instead of using #br_img, could i use a class there I wonder? – Stan Jul 16 '14 at 20:39
  • Yes, you can use a class there. – JRulle Jul 16 '14 at 20:44
  • Here is an expanded example that changes the image on each li tag between a series of 2 (imagine expanding from 2 to 4 to reach your use case) [JSFIDDLE](http://jsfiddle.net/gYjU2/3/) – JRulle Jul 16 '14 at 21:10
  • Hmm, your first function works good when I updated my codepen: [link](http://codepen.io/jsegarra/pen/dlLtq). And is going to make life easy updating my HTML. But for some reason I'm not getting to work in my site. I wonder what it's getting hung up on? I've tried wrapping it in $(document).ready()... as well as within the function that pulls up this section of the page and can't seem to get it going. I'll play with it some more and let you know if I get it to work. – Stan Jul 17 '14 at 15:32
  • @Stan, Do you have a link to the site where it is not working? – JRulle Jul 17 '14 at 15:46
  • Currently I have a link to the production site itself, but not with this in it. I'll add that and put up a link. – Stan Jul 17 '14 at 16:13
  • Your issue could be preloading images: See edited [FIDDLE](http://jsfiddle.net/jrulle/gYjU2/5/) example. If you find that this is your problem, you can read up more on [preloading images here](http://www.htmlgoodies.com/tutorials/web_graphics/article.php/3480001) – JRulle Jul 17 '14 at 16:18
  • Yea i wondered about that at one point, I'll look into that, thanks! – Stan Jul 17 '14 at 17:04
  • Sorry it took a while, but the non-working script is up here: [link](http://67.154.100.35/testweb/Main%20working/Fullsiteprjimgs.html), on the site go to Project>Civic>Blackstone River Valley is the one I'm testing it on. The script is in the file imageFade.js; let me know if you spot the problem. I've tried it a number of ways and can't get it going. – Stan Jul 18 '14 at 13:31
  • This is the error I am getting when trying to switch images: `Uncaught ReferenceError: e is not defined` (in the inspector in google chrome). Try removing or commenting out this line of your javascript `e.preventDefault()` in the `$('.imgNumerals li').click(function () {...` – JRulle Jul 18 '14 at 13:34
  • Yes, that worked perfectly after I commented it out. I ran it across multiple divs and its working off the classes. Thank you so much for looking at that! The only problem is when you go to the next div(project) it starts out on the last image from the past section, any idea? – Stan Jul 18 '14 at 19:19
  • Try adding the `.swap` class to the `.projectTitle` `LI`'s. Also add the `data-img` attribute of the image you want each project to start with. – JRulle Jul 18 '14 at 20:03
  • I tried that but still no go, I also tried to add in .end() or .unbind(), but i've never used those so I have to research a little bit more I guess. – Stan Jul 18 '14 at 20:16
  • @stan, try an alternative class like `.swap2` as I think you will need to basically duplicate the effect of `$('.swap').click(...` and bring the javascript from your `onclick="..."` out of the LI's and into the jQuery. Don't forget that you will need the data-image attribute added to the `.projectTitle` `LI`'s -- other than that it may be a bit of trial and error as you have multiple event triggers/listeners/handler going on all over the page (you can always try removing something and if it works without it you have found the conflict) – JRulle Jul 18 '14 at 20:24
  • Ok, I'll keep playing with it. I'll try the different class thing and see if that works. Also the little Arrow is what takes you back to the previous menu to pick another project, so I was trying to write a new function for that click to basically reset it, but haven't figured that out yet. I appreciate all your help! – Stan Jul 18 '14 at 20:53
0

oh my way seems a lot more long winded than @JRulle but i'll post anyway as it's a different take on it.

one of the things i first noticed is that by just replacing the src of the img a delay can be noticed where the image is downloaded, this can affect the look of the fade in as the image fades in before loading then suddenly appears once loaded.

The other thing I was thinking is that with 48 projects it would be a right bitch to have to add all those click listeners so went with a solution that will do everything just based on a list of images you want to display.

(working codepen can be found here)

declare all images in an array, if your page is being built dynamically this could be the only thing you need to build.

var images =[
"http://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Cathedral_Group_panorama_from_Cathedral_Group_Scenic_Turnout2.JPG/800px-Cathedral_Group_panorama_from_Cathedral_Group_Scenic_Turnout2.JPG",
    "http://kerlabs.net/wp-content/uploads/2014/03/Scenic-Waterfall-HD-Wallpaper.jpg",
    "http://kerlabs.net/wp-content/uploads/2014/03/Blue-Ocean-Scenic-HD-Wallpaper-.jpeg",
    "http://kerlabs.net/wp-content/uploads/2014/03/Beauty-Blue-scenic-wallpaper.jpeg"
];

//preload images courtesy of http://stackoverflow.com/a/476681/2737978
function preload(arrayOfImages) {
    $(arrayOfImages).each(function() {
        $('<img/>')[0].src = this;
    });
}
preload(images);

//the next section are just some helpers to move images left/right or go to a specific image //use a pointer to know what image currently on

var pointer = 0;


incrementPointer = function() {
    if (pointer == images.length - 1) {
        pointer = 0;
    } else {
        pointer++;
    }
}

deincrementPointer = function() {
    if (pointer == 0) {
        pointer = images.length - 1;
    } else {
        pointer--;
    }
}
deincrementImage = function() {
        deincrementPointer();
        changeImage(pointer);
    }

incrementImage = function() {
    incrementPointer();
    changeImage(pointer);
}

//change image is where the actually image is swapped over using the complete call back to
//change the image and fade in after the fade out has completed, because the images are
//preloaded flicker should not be noticed

changeImage = function(index) {
    $imgPlaceHolder.fadeOut("slow", function() {
        $imgPlaceHolder.attr("src", images[index])
        $imgPlaceHolder.fadeIn("slow");
    });

}



var $imgPlaceHolder = $("#br_img");


$(document).ready(function() {
    //first image is placed in straight away
    $imgPlaceHolder.attr("src", images[pointer]);


    //listener setup on the backbutton
    $("a.arrowBack").click(function(event) {
        event.preventDefault();
        deincrementImage();

    });

//the li's are dynamically added and listeners attached based on the number of images
//using the html of the li is a bit ugly but this could be added to a data attribute instead

var index = 0;
    images.forEach(function() {
        $("<li>", {
            html: index + 1
        }).on("click", function() {
            changeImage(parseInt($(this).html()) - 1);
        }).appendTo('.imgNumerals');
        index++;

    });
});
Quince
  • 14,790
  • 6
  • 60
  • 69
  • Thanks for your interpretation, seems to work good. But, @JRulle answer seems like it will make most sense with what I already have, if i can get it to work outside of my codepen and with my other jQuery files. I'll definitely revisit your suggestion if I can't. – Stan Jul 17 '14 at 15:34