0

I use javascript function for each menu and call that function onClick event. What i face is the image is not changing smoothly, Some times its loading slowly.

Lets consider 2 links each link calls a function for changing the background of the body

This is how i change now

function events(){
   $("body").css('background-image','url(./wp-content/Uploads/img3.jpg)');
}

function projects(){
   $("body").css('background-image','url(./wp-content/Uploads/img2.jpg)');
   return false;
}

HTML

<li id="projectsm"><a href="#projects" onClick="projects();" class="stylish">Projects</a></li>
<li id="eventsm"><a href="#events" onClick="events();" class="stylish">Events</a></li>

So when i click the menu it must transform like fade out or something smoothly not like flashing

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 1
    possible duplicate of [fade in background jquery](http://stackoverflow.com/questions/17825194/fade-in-background-jquery) – Pete Sep 29 '14 at 12:53

2 Answers2

1

If I understand your problem, you can change body background image with jQuery on click on a link, but it's not smooth / fast enough.

I think it's mainly because when you change your background, the new background isn't loaded yet. So it have to load, then to change when it's loaded.

Solutions :

  • you can load all the backgrounds on document load

  • you can load the new background and then call your switch function

In both case, you can use ImagesLoaded plugin to load your images when you want (https://github.com/desandro/imagesloaded).

Then if you want a smooth transition, you can use CSS3 Transition on your body selector :

transition: background-image 1s ease-in-out;

But I'm not sure transition works on background-image property...

enguerranws
  • 8,087
  • 8
  • 49
  • 97
0

Try this code, if that's what you want:

You need load image first, then use javascript.

HTML:

<img src="http://lorempixel.com/400/200/city" alt="" width="0" height="0" />
<img src="http://lorempixel.com/400/200/people" alt="" width="0" height="0" />
<ul>
    <li id="projectsm">Projects</li>
    <li id="eventsm">Events</li>
</ul>

JS:

$(function(){
    $('#projectsm').click(function(){
        $('body').css('background-image','url(http://lorempixel.com/400/200/city)')
    });
    $('#eventsm').click(function(){
        $('body').css('background-image','url(http://lorempixel.com/400/200/people)')
    });
});

and for smooth transition, use css3 transition property

CSS:

body{
    background-image:url(http://lorempixel.com/400/200/animals);
    background-repeat:no-repeat;
    background-size:cover;
    -webkit-transition: background 1s ease-in-out;
    -moz-transition: background 1s ease-in-out;
    -ms-transition: background 1s ease-in-out;
    -o-transition: background 1s ease-in-out;
    transition: background 1s ease-in-out;
}

http://jsfiddle.net/sL8q7nbb/1/

maťo
  • 1,225
  • 8
  • 16