Diwas
Diwas

Reputation: 3

how to move css element with scrolling left with Jquery?

$(document).ready(function(){   

  $(window).scroll(function(){  

    var lScoll = $(this).scrollLeft();

    $('.logo').css({

      'transform' : 'translate(500px)'}, 5000);

  });

});

.logo is an image div I want to move to left as I scroll left. I gave up and tried to just delay the transform. How do i do either of them? Thank you. Here is my HTML:

<header>   

    <div class="logo">
      <img src="img/visitLogo.png">

    </div>
  </div>

</header>

Upvotes: 0

Views: 367

Answers (1)

user4157770
user4157770

Reputation:

$(document).ready(function(){   

  $(window).scroll(function(){  

    var lScoll = $(this).scrollLeft();

    $('.logo').css({

      'transform' : 'translate(500px)'}, 5000);

  });

});

This code says that when the DOM has loaded, run a function, then whenever the window is scrolled, create a variable which targets the window (this = window in this code) and run a scrollLeft function (which will always be 0 unless you have an overflow on the x that makes a side scrolling bar).

To fix these issues, I have changed the JS as you can see:

$(window).scroll(function() {
            $('.logo').css({
                        'transform': 'translateX(500px)'
            });

});

and in the CSS, I have set the translateX to be at 0 in the beginning (so that it is animateable) and I also set the transition speed to 0.25 seconds with an ease-in-out timer, as you can see here:

header {
  margin: 250px auto;
  width: 80vw;
  position: relative;
}
header .logo {
  -webkit-transition: all 0.25s ease-in-out;
          transition: all 0.25s ease-in-out;
  -webkit-transform: translateX(0);
      -ms-transform: translateX(0);
          transform: translateX(0);
}

Note that I have the browser prefixes for cross browser compatibility (thanks to autoprefixer) and I also set the header to have some basic styles but you don't need these, they were just so that the example looked decent.

Here is my fixes with full code available to you:

Codepen with fixes and working code

Upvotes: 1

Related Questions