Changing image on scroll using jQuery in PHP not working - javascript

I have a php website, I have a background image of a road, and 2 images of a character, when the user scrolls, I want the images to change till the section is over, such that it looks like the character is moving.
I did the following code in jQuery:
$(document).ready(function() {
$(window).on("scroll", function() {
console.log($(this).scrollTop())
<?php for($i=30;$i<=2500;$i++){ ?>
if($(this).scrollTop() >= <?=$i?>){
// set to new image
$(".bgimg img").attr("src","char1.png");
} else {
//back to default
$(".bgimg img").attr("src","char2.png");
}
<?php } ?>
})
})
.bgimg {
background-image: url('road.png');
height: 2500px;
background-size:cover;
width:50%
}
<div class="container" style="text-align: -webkit-center;">
<div class="row">
<p>This is a test </p>
</div>
<div class="row bgimg" >
<img src="char1.png" id="chara">
</div>
</div>
however it doesn't work. Can anyone please tell me what is wrong?
Thanks in advance

I don't know if this can answer because I'm not sure I understood what you want but here are examples that may be able to help you (without PHP loop)
<script>
$(function(){
$(window).on("scroll", function() {
if($(this).scrollTop()>30) $(".bgimg img").attr("src","char2.png");
else $(".bgimg img").attr("src","char1.png");
});
});
</script>
With the script above the image changes with the threshold of 30
--------------------------------------------------------------------------------------------------------
With the script below the image changes alternately as the user "scrolls" the page.
With the following HTML code
<div id="characterDiv"><img id="characterImage" src="char1.png"></div>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
With a long text page to have a high enough window
</p>
With this CSS
<style type="text/css">
html { font-family:Arial; font-size: 0.9em; }
p { width: 50%; text-align: justify; }
#characterDiv {
position: fixed;
right: 50%;
top: 50%;
width: 8em;
margin-top: -2.5em;
}
</style>
And this JQuery Script (without PHP Loop but with Mathematics)
<script>
$(function(){
$(window).on("scroll", function() {
let pitch = 150;
// Display for Test
console.log($(this).scrollTop()+' -> '+(Math.round($(this).scrollTop()/pitch))%2);
// This calculation gives alternately 0 or 1
if((Math.round($(this).scrollTop()/pitch))%2==0) $("#characterImage").attr("src","char2.png");
else $("#characterImage").attr("src","char1.png");
});
});
</script>

Related

Using the duration of mouse press for scrolling

I coded this:
$("#scroll-to-left-button").on("mousedown", function() {
var x = $("#scroll-area").scrollLeft();
$("#scroll-area").scrollLeft(x - 10);
});
$("#scroll-to-right-button").on("mousedown", function() {
var x = $("#scroll-area").scrollLeft();
$("#scroll-area").scrollLeft(x + 10);
});
#container {
width: 50%;
height: 100px;
background-color: grey;
position: relative;
}
#scroll-area {
white-space: nowrap;
overflow-x: auto;
height: 100%;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="container">
<div id="scroll-area">
<div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
</div>
</div>
<button id="scroll-to-left-button">Scroll to left</button>
<button id="scroll-to-right-button">Scroll to right</button>
You need to click the buttons pretty often to navigate through this container. Is there a way to let it based on the duration of the mouse press? Like if you keep the mouse pressed, it continues constantly scrolling? And if you stop, it stops.
Would be happy if someone could help me.
Here's a working solution. Also your code was a bit wet, so I refactored it a bit. You only need one mousedown event listener.
let interval;
$('.scroll-btn').on('mousedown', ({ target }) => {
const type = $(target).attr('id');
interval = setInterval(() => {
var x = $('#scroll-area').scrollLeft();
$('#scroll-area').scrollLeft(type === 'left' ? x - 10 : x + 10);
}, 50);
});
$('.scroll-btn').on('mouseout mouseup', () => clearInterval(interval));
#container {
width: 50%;
height: 100px;
background-color: grey;
position: relative;
}
#scroll-area {
white-space: nowrap;
overflow-x: auto;
height: 100%;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="container">
<div id="scroll-area">
<div id="text">
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua.
</div>
</div>
</div>
<button id="left" class="scroll-btn">Scroll Left</button>
<button id="right" class="scroll-btn">Scroll Right</button>
Well, the mousedown and mouseup make a good pair, although you have used only mousedown :)
Here's a sample how it could be done.
Note that there're couple other things that could be done to this code for it to look nicer:
.on(... is not probably needed, you could just write it as .mousedown(...
the code for the right and left buttons look really similar, you could unite these blocks in one and distinguish by an additional attrubute (let's say like move="10" for the right button and move="-10" for the left one, and then just getting this value in order to add it to scrollLeft)
var tmr;
$(".scroll-button").mousedown(function() {
//let's setup the timer here...
move = +$(this).attr("move");
tmr = setInterval(function(){
$("#scroll-area")[0].scrollLeft+=move;
}, 250)
});
$(".scroll-button").mouseup(function() {
// and destroy the timer here
clearInterval(tmr);
});
#container {
width: 50%;
height: 300px;
background-color: grey;
position: relative;
}
#scroll-area {
white-space: nowrap;
overflow-x: auto;
height: 100%;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="container">
<div id="scroll-area">
<div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
</div>
</div>
<button class="scroll-button" move="-10">Scroll to left</button>
<button class="scroll-button" move="10">Scroll to right</button>

GSAP ScrollTrigger animations not working with Locomotive JS (until window is resized)

I have sections across my site which are using ScrollTrigger. Once I implemented Locomotive JS, all of my ScrollTrigger animations stopped working.
I read through the forums and saw that you need to update() ScrollTrigger when Locomotive is scrolling. I implemented this and saw no results.
Then, I resized the window and my ScrollTrigger animations that were in view, they started working.
In short, animations trigger on resize, but not on page load.
I've implemented update() and also tried refresh(), but no luck.
Demo (fiddle showing issue here also):
$(function() {
gsap.registerPlugin(ScrollTrigger);
function animateFrom(elem, direction) {
direction = direction || 1;
var x = 0, y = direction * 100;
if(elem.classList.contains("gsap_reveal--fromLeft")) {
x = -100;
y = 0;
} else if (elem.classList.contains("gsap_reveal--fromRight")) {
x = 100;
y = 0;
}
elem.style.transform = "translate(" + x + "px, " + y + "px)";
elem.style.opacity = "0";
gsap.fromTo(elem, { x: x, y: y, autoAlpha: 0 }, {
duration: 2,
x: 0,
y: 0,
autoAlpha: 1,
ease: "expo",
overwrite: "auto"
});
}
function hide(elem) {
gsap.set(elem, { autoAlpha: 0 });
}
gsap.utils.toArray(".gsap_reveal").forEach(function(elem) {
hide(elem); // assure that the element is hidden when scrolled into view
ScrollTrigger.create({
trigger: elem,
onEnter: function() { animateFrom(elem) },
onEnterBack: function() { animateFrom(elem, -1) },
onLeave: function() { hide(elem) } // assure that the element is hidden when scrolled into view
});
});
const pageContainer = document.querySelector("[data-scroll-container]");
const scroll = new LocomotiveScroll({
el: pageContainer,
smooth: true
});
// each time locomotive Scroll updates, tell ScrollTrigger to update too (sync positioning)
scroll.on(pageContainer, ScrollTrigger.update);
// tell ScrollTrigger to use these proxy methods for the ".data-scroll-container" element since Locomotive Scroll is hijacking things
ScrollTrigger.scrollerProxy(pageContainer, {
scrollTop(value) {
return arguments.length ? scroll.scrollTo(value, 0, 0) : scroll.scroll.instance.scroll.y;
}, // we don't have to define a scrollLeft because we're only scrolling vertically.
getBoundingClientRect() {
return {top: 0, left: 0, width: window.innerWidth, height: window.innerHeight};
}
});
window.addEventListener("load", function (event) {
ScrollTrigger.refresh();
});
ScrollTrigger.addEventListener("refresh", () => scroll.update());
ScrollTrigger.refresh();
});
.hero {
min-height: 1000px;
background: lightblue;
display: flex;
align-items: center;
}
.textImageRepeater {
overflow: hidden;
padding: 120px 0 160px 0;
}
.textImageRepeater__intro {
margin-bottom: 66px;
}
.textImageRepeater__layout--row {
flex-direction: row !important;
}
.textImageRepeater__layout--rowReverse {
flex-direction: row-reverse !important;
}
.textImageRepeater__item {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
padding-top: 70px;
justify-content: space-between;
}
.textImageRepeater__header {
margin: 17px 0;
}
.textImageRepeater__graphic {
margin: 0;
}
.textImageRepeater__text, .textImageRepeater__graphic {
flex-basis: 50%;
}
.textImageRepeater__text {
max-width: 500px;
}
.c-scrollbar_thumb{
background-color: #5D209F!important;
width: 7px;
margin: 2px;
opacity: 1;
border-radius: unset;
mix-blend-mode: multiply;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/locomotive-scroll#4.1.3/dist/locomotive-scroll.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/locomotive-scroll#4.1.3/dist/locomotive-scroll.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/ScrollTrigger.min.js"></script>
<div data-scroll-container>
<div data-scroll-section>
<section class="hero">
<div class="container">
<div class="row justify-content-center justify-content-xl-between">
<div class="col-12 col-md-10 col-lg-9 col-xl-5">
<div class="hero__text text-center text-xl-start">
<h1 class="hero__title" data-scroll data-scroll-speed="2">Title</h1>
</div>
</div>
</div>
</div>
</section>
<section class="textImageRepeater">
<div class="container">
<div class="row">
<div class="col-12">
<div class="textImageRepeater__item textImageRepeater__layout--row">
<div class="textImageRepeater__text text-center text-md-start gsap_reveal gsap_reveal--fromRight">
<div class="textImageRepeater__copy">
<h2>Header</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
<div class="textImageRepeater__graphic text-center gsap_reveal gsap_reveal--fromLeft">
<img class="textImageRepeater__image" src="https://picsum.photos/200/300" alt="placeholder-image" loading="lazy">
</div>
</div>
<div class="textImageRepeater__item textImageRepeater__layout--rowReverse">
<div class="textImageRepeater__text text-center text-md-start gsap_reveal gsap_reveal--fromRight">
<div class="textImageRepeater__copy">
<h2>Header</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
<div class="textImageRepeater__graphic text-center gsap_reveal gsap_reveal--fromLeft">
<img class="textImageRepeater__image" src="https://picsum.photos/200/300" alt="placeholder-image" loading="lazy">
</div>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
Test 1
What I've realised is, if I comment out all my locomotive js and run:
$(window).on('scroll', function() {
console.log("test");
});
The logs will show, but they do not when locomotive is active.
Unsure if this may indicate what's going wrong?
Test 2
At the end of my snippet, I ran the following to check if refresh() was even running and it was returning the else statement. Again, not sure why.
if (ScrollTrigger.refresh()){
console.log("true");
} else{
console.log("false");
}
Steps to recreate:
Open this fiddle
Widen the output box to something wide (i.e. 1300px)
Run the fiddle
Scroll down and you'll see the elements not loading
Resize the output box to something smaller
The scrollTrigger animations now appear
Here is a gif showcasing the issue:
These are what I've tried to get the animation run.
1. Let ScrollTrigger know about the new scroller.
As you're using Locomotive scroll that means the native scroll which ScrollTrigger is based on is removed. So we bring it back by doing this:
ScrollTrigger.create({
scroller: "[data-scroll-container]" // this is what you're missing
// your other options
});
Read the docs for ScrollTrigger > scroller
2. Assign the ScrollTrigger tween at last.
I'm not really sure but the reason could be simply that the tweens need to be assigned once the whole scrolling system has been set.
// init Locomotive
// ...
// create ScrollTrigger
gsap.utils.toArray(".gsap_reveal").forEach(function(elem) {
hide(elem); // assure that the element is hidden when scrolled into view
ScrollTrigger.create({
scroller: "[data-scroll-container]",
trigger: elem,
onEnter: function() { animateFrom(elem) },
onEnterBack: function() { animateFrom(elem, -1) },
onLeave: function() { hide(elem) } // assure that the element is hidden when scrolled into view
});
});
See JSFiddle

How to make a scrollable section inside div that fills in all the remaining space of said div

I have a div with a bunch of different sections, one of which is a scrollable list within the div.
The scrollable area varies depending on the screen size and needs to occupy all the remaining space of the parent. So far, I only know how to make it scroll if I specify the scrollable div's height. This of course, will not have a once size fits all when dealing with different screen sizes.
If I alternatively set my scrollable div's height to 100%, I then of course lose my ability to scroll. So that's no good either.
How can I solve this?
Here is a sample app illustrating the problem:
const App = () => {
return (
<div className="container">
<div>
<h2>My Content</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<h3>Scrollable section that must fill in the rest of the space</h3>
<div className="scrollable-div">
{[...Array(50).keys()].map((_, index) => (
<div>item {index}</div>
))}
</div>
</div>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
.container {
height: 500px;
border: 2px solid black;
overflow: hidden;
}
.scrollable-div {
overflow: auto;
border: 3px solid red;
/*
this all works fine, but I need the scroll section to go all the way to the end of the parent div,
regardless of the screen size. How can I do this without setting a fixed height here?
*/
height: 250px;
/*
the alternative, which would allow this div to expand all the way down to the reminder of the parent
is set height to 100%, however then I lose my ability to scroll.
*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Run snippet, and click 'full page' then scale browser and scrolling area should be dynamic in height. Only tested in Chrome btw.
const App = () => {
return (
<div className="container">
<div className="inner">
<h2>My Content</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<h3>Scrollable section that must fill in the rest of the space</h3>
<div className="scrollable-div">
{[...Array(50).keys()].map((_, index) => (
<div>item {index}</div>
))}
</div>
</div>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
.container {
display: flex;
flex-direction: column;
border: 2px solid #2B3239;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.inner {
padding: 12px;
background: #EFF2F5;
min-height: 0;
display: flex;
flex-direction: column;
}
.scrollable-div {
background: white;
border: 2px solid #FF6F6F;
flex-grow: 1;
overflow: scroll;
padding: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Replicate input scroll on div

I'm trying to replicate a input horizontal scroll on a div element, so whenever the user move along the input the div element scrolls exactly the same as the input.
My problem is with Chrome as it seems the input has a different scroll behavior, causing the scrollLeft value to be different in both elements. In Firefox it works as expected.
Is there any way to achieve this in Chrome without using jQuery or other libraries? or am I asking the impossible?
var theTextDiv = document.getElementById("the-text");
var theText = document.getElementById("the-text-input");
function keepScroll(txt) {
theTextDiv.scrollLeft = theText.scrollLeft;
}
theText.addEventListener("blur", function() { keepScroll("blur"); });
theText.addEventListener("change", function() { keepScroll("change"); });
theText.addEventListener("focus", function() { keepScroll("focus"); });
theText.addEventListener("input", function() { keepScroll("input"); });
theText.addEventListener("keydown", function() { keepScroll("keydown"); });
theText.addEventListener("keyup", function() { keepScroll("keyup"); });
theText.addEventListener("scroll", function() { keepScroll("scroll"); });
theText.addEventListener("select", function() { keepScroll("select"); });
#the-text {
border: 1px solid red;
max-width: 98px;
font-size: 14px;
overflow-x: scroll;
word-wrap: break-word;
white-space: nowrap;
font-family: "Times New Roman", Times, serif;
padding: 1px;
margin-right: 10px;
}
#the-text-input {
border: 1px solid red;
width: 100px;
font-size: 14px;
font-family: "Times New Roman", Times, serif;
}
<div id="the-text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<input type="text" id="the-text-input" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." />
EDIT:
I tried the above code on Chrome 77 on a Mac and it works as expected, there's no gap between both elements, and I'm starting to think this is a Windows problem rather than a Chrome problem
EDIT(2):
After restarting my PC all work as expected (seriously) maybe some chrome cache was causing to have a weird behavior
This probably has to do with paddings and borders on the input and/or the div, and as it looks like it's working fine in Chrome 77, you either forgot to add some code in the example you posted or the default styles for those elements are also playing a role here.
In any case, my suggestion would be to remove margins, paddings and borders from both elements and adding a wrapping div with those instead (red example).
You can also use box-sizing: border-box, keep those styles and avoid the wrapper, but padding behaves differently in an input, as content in the padding area is not visible (blue example).
Lastly, your code to update the scroll was not working properly on blur, as when the event fires the scroll on the input hasn't been reset to 0 yet. Wrapping it with setTimeout or window.requestAnimationFrame solves the issue. Additionally, the latter will also make the update much smoother and in-sync.
const text = document.getElementById('text');
const input = document.getElementById('input');
function updateScroll() {
// Scroll not updated on blur without requestAnimationFrame
// or setTimeout:
requestAnimationFrame(() => text.scrollLeft = input.scrollLeft);
}
input.addEventListener('blur', updateScroll);
input.addEventListener('change', updateScroll);
input.addEventListener('focus', updateScroll);
input.addEventListener('input', updateScroll);
input.addEventListener('keydown', updateScroll);
input.addEventListener('keyup', updateScroll);
input.addEventListener('scroll', updateScroll);
input.addEventListener('select', updateScroll);
const textAlternative = document.getElementById('text-alternative');
const inputAlternative = document.getElementById('input-alternative');
function updateScrollAlternative() {
// Scroll not updated on blur without requestAnimationFrame
// or setTimeout:
requestAnimationFrame(() => textAlternative.scrollLeft = inputAlternative.scrollLeft);
}
inputAlternative.addEventListener('blur', updateScrollAlternative);
inputAlternative.addEventListener('change', updateScrollAlternative);
inputAlternative.addEventListener('focus', updateScrollAlternative);
inputAlternative.addEventListener('input', updateScrollAlternative);
inputAlternative.addEventListener('keydown', updateScrollAlternative);
inputAlternative.addEventListener('keyup', updateScrollAlternative);
inputAlternative.addEventListener('scroll', updateScrollAlternative);
inputAlternative.addEventListener('select', updateScrollAlternative);
body {
margin: 0;
}
.box {
position: relative;
display: block;
width: 50%;
box-sizing: border-box;
/* Moved styles here: */
border: 3px solid red;
padding: 8px;
margin: 8px auto 0;
}
#text,
#input,
#text-alternative,
#input-alternative {
display: block;
width: 100%;
font-size: 14px;
font-family: monospace;
outline: none;
}
#text,
#input {
/* Removed margin, padding and borders: */
border: 0;
padding: 0;
margin: 0;
}
#text-alternative,
#input-alternative {
width: 50%;
box-sizing: border-box;
/* Keep styles here thanks to box-sizing, but behaves differently: */
border: 3px solid blue;
padding: 8px;
margin: 8px auto 0;
}
#text,
#text-alternative {
word-wrap: break-word;
white-space: nowrap;
/* No need to keep it visible unless you want to scroll manually too: */
overflow-x: hidden;
}
<div class="box">
<div id="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
</div>
<label class="box">
<input id="input" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." />
</label>
<div id="text-alternative">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<input id="input-alternative" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." />

Add class to div in rotating carousel style

I have 3 identical divs and I want to add a class to one of those divs every 5 seconds one a rotating carousel type thing.
The following JSFiddle is what I have atm and I want the :hover styles to to be added to one of those divs every 5 seconds in a rotating sequence but still work as an on hover; JSFiddle
.action {
padding: 10px 50px 10px 10px;
background-color: #eaeaea;
color: #525454;
}
.action:hover {
background-color: #b5b5b5;
color: #000;
}
.action h3 {
margin: 0 0 10px 0;
}
.action .corner {
position: absolute;
width: 0;
height: 0;
border-bottom: 50px solid #db7575;
border-left: 50px solid transparent;
bottom: 0;
right: 0;
}
.action:hover .corner {
border-bottom: 50px solid #CC0000;
}
.action i {
position: absolute;
margin-left: -20px;
margin-top: 27px;
color: #fff;
}
<div class="row">
<a href="#">
<div class="col-md-4 action">
<h3> Title 1 </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <span class="corner "><i class="fa fa-arrow-right"></i></span>
</div>
</a>
<a href="#">
<div class="col-md-4 action">
<h3> Title 2 </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <span class="corner "><i class="fa fa-arrow-right"></i></span>
</div>
</a>
<a href="#">
<div class="col-md-4 action">
<h3> Title 3 </h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p> <span class="corner "><i class="fa fa-arrow-right"></i></span>
</div>
</a>
</div>
Something like this ?
http://jsfiddle.net/15od56d3/
CSS
.action:hover,.my_turn { background-color: #b5b5b5; color: #000;}
Javascript
var myTurn = 0;
setInterval(function(){
var i = 0;
$(".action").each(function(){
if(i==myTurn)
$(this).addClass("my_turn");
else
$(this).removeClass("my_turn");
i++;
});
myTurn = (myTurn + 1)%3 ;
},5000);
What I don't get in the accepted answer is that the carousel doesn't pause when the mouse hovers over an item. This is very confusing, especially since the same style is applied. I would create a jQuery object of the rows and use the available jQuery functions to walk over/select them and apply the a class for the hover instead of using the css property.
See the JSFiddle for a demo
var $rows = $('.action');
var $start= $rows.first(); // select one to start with (can be any of the elements in the set)
var $current = $start;
var interval;
var hover = function() {
$current.removeClass('hover');
$current = $rows.eq($rows.index($current)+1);
if (!$current.length) {
$current = $rows.eq($rows.index($start));
}
$current.addClass('hover');
};
The carousel should keep the expected direction and move on from where the hover-style was last applied; from the hovered element (as this is the most natural behavior imho):
$('.action').mouseover(function() {
window.clearInterval(interval);
$current.removeClass('hover');
$current = $(this).addClass('hover');
}).mouseout(function() {
interval = window.setInterval(hover, 2000);
});
$start.addClass('hover').mouseout(); // apply the class immediately to the first row

Categories

Resources