trigger 'click' event every 3 seconds without clicking on the next button? - javascript

I have a liquid carousel slider set up on one of my websites located over here http://www.edhubdemo.com/wp/. The slider is located under the Our Works and the Our Clients' area and currently users can scroll through the works by clicking on the next/previous buttons. Now what I want to do is that the 'click' function should be triggered itself after every 3 seconds so that the slider moves to the next 4 set of works itself. I tried using the trigger function but I guess I couldn't integrate it correctly. Here's the code inside the liquid carousel javascript file:
(function($){
$.fn.liquidcarousel = function(options) {
var defaults = {
duration: 10000
};
var options = $.extend(defaults, options);
return this.each(function() {
var divobj = $(this);
$(divobj).css('overflow', 'hidden');
$('> .wrapper', divobj).css('overflow', 'hidden');
$('> .wrapper', divobj).css('float', 'left');
$('> .wrapper > ul', divobj).css('float', 'left');
$('> .wrapper > ul', divobj).css('margin', '0');
$('> .wrapper > ul', divobj).css('padding', '0');
$('> .wrapper > ul', divobj).css('display', 'block');
$('> .wrapper > ul > li', divobj).css('display', 'block');
$('> .wrapper > ul > li', divobj).css('float', 'left');
var visiblelis = 0;
var totallis = $('> .wrapper > ul > li', this).length;
var currentposition = 0;
var additionalmargin = 0;
var totalwidth = 0;
$(window).resize(function(e){
var divwidth = $(divobj).width();
var availablewidth = divwidth;
var heighest = 0;
$('> .wrapper > ul > li', divobj).css("height", "auto");
$('> .wrapper > ul > li', divobj).each(function () {
if ( $(this).outerHeight() > heighest ) {
heighest = $(this).outerHeight();
}
});
$(divobj).height(heighest);
$('> .wrapper', divobj).height(heighest);
$('> .wrapper > ul', divobj).height(heighest);
$('> .wrapper > ul > li', divobj).height(heighest);
var liwidth = $('> .wrapper > ul > li:first', divobj).outerWidth(true);
var originalmarginright = parseInt($('> .wrapper > ul > li', divobj).css('marginRight'));
var originalmarginleft = parseInt($('> .wrapper > ul > li', divobj).css('marginLeft'));
totalwidth = liwidth + additionalmargin;
previousvisiblelis = visiblelis;
visiblelis = Math.floor((availablewidth / liwidth));
if (visiblelis < totallis) {
additionalmargin = Math.floor((availablewidth - (visiblelis * liwidth))/visiblelis);
} else {
additionalmargin = Math.floor((availablewidth - (totallis * liwidth))/totallis);
}
halfadditionalmargin = Math.floor(additionalmargin/2);
totalwidth = liwidth + additionalmargin;
if (visiblelis > previousvisiblelis || totallis <= visiblelis) {
currentposition -= (visiblelis-previousvisiblelis);
if (currentposition < 0 || totallis <= visiblelis ) {
currentposition = 0;
}
}
$('> .wrapper > ul', divobj).css('marginLeft', -(currentposition * totalwidth));
if (visiblelis >= totallis || ((divwidth >= (totallis * liwidth)) && options.hidearrows) ) {
if (options.hidearrows) {
$('> .prev', $(divobj).parents(".widget")).hide();
$('> .next', $(divobj).parents(".widget")).hide();
additionalmargin = Math.floor((divwidth - (totallis * liwidth))/totallis);
halfadditionalmargin = Math.floor(additionalmargin/2);
totalwidth = liwidth + additionalmargin;
$('> .wrapper > ul > li', divobj).css('marginRight', originalmarginright + halfadditionalmargin);
$('> .wrapper > ul > li', divobj).css('marginLeft', originalmarginleft + halfadditionalmargin);
}
$('> .wrapper', divobj).width(totallis * totalwidth);
$('> ul', divobj).width(totallis * totalwidth);
$('> .wrapper', divobj).css('marginLeft', 0);
currentposition = 0;
} else {
$('.prev', $(divobj).parents(".widget")).show();
$('.next', $(divobj).parents(".widget")).show();
$('> .wrapper', divobj).width(visiblelis * totalwidth);
$('> ul', divobj).width(visiblelis * totalwidth);
}
});
$('.next', $(divobj).parents(".widget")).click(function(){
if (totallis <= visiblelis) {
currentposition = 0;
} else if ((currentposition + (visiblelis*2)) < totallis) {
currentposition += visiblelis;
} else if ((currentposition + (visiblelis*2)) >= totallis -1) {
currentposition = totallis - visiblelis;
}
$('> .wrapper > ul', divobj).stop();
$('> .wrapper > ul', divobj).animate({'marginLeft': -(currentposition * totalwidth)}, options.duration);
$('.prev', $(divobj).parents(".widget")).click(function(){
if ((currentposition - visiblelis) > 0) {
currentposition -= visiblelis;
} else if ((currentposition - (visiblelis*2)) <= 0) {
currentposition = 0;
}
$('> .wrapper > ul', divobj).stop();
$('> .wrapper > ul', divobj).animate({'marginLeft': -(currentposition * totalwidth)}, options.duration);
});
$('.next', $(divobj).parents(".widget")).dblclick(function(e){
e.preventDefault();
clearSelection();
});
$('.prev', $(divobj).parents(".widget")).dblclick(function(e){
e.preventDefault();
clearSelection();
});
function clearSelection() {
if (document.selection && document.selection.empty) {
document.selection.empty();
} else if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
$(window).resize();
});
This is the part of the code which moves the slider forward when the next button is clicked:
$('.next', $(divobj).parents(".widget")).click(function(){
if (totallis <= visiblelis) {
currentposition = 0;
} else if ((currentposition + (visiblelis*2)) < totallis) {
currentposition += visiblelis;
} else if ((currentposition + (visiblelis*2)) >= totallis -1) {
currentposition = totallis - visiblelis;
}
$('> .wrapper > ul', divobj).stop();
$('> .wrapper > ul', divobj).animate({'marginLeft': -(currentposition * totalwidth)}, options.duration);
And this is the part of the code which makes the slider move backwards when the previous button is clicked:
$('.prev', $(divobj).parents(".widget")).click(function(){
if ((currentposition - visiblelis) > 0) {
currentposition -= visiblelis;
} else if ((currentposition - (visiblelis*2)) <= 0) {
currentposition = 0;
}
$('> .wrapper > ul', divobj).stop();
$('> .wrapper > ul', divobj).animate({'marginLeft': -(currentposition * totalwidth)}, options.duration);
});

select your element in jQuery
var next = $('.next', $(divobj).parents(".widget"));
then call a click on it every 3 secs
setInterval(next.click, 3000);
However the best would be to create a function for this task (sliding the carousel), and call that function from a click. Then you can call that function directly instead of simulating a click.

Simulate a mouse click event on .next by using createEvent("MouseEvents")
$('.next', $(divobj).parents(".widget")).each(function (idx, elm) {
var ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
elm.dispatchEvent(ev);
});
I did .each because a class is non-unique, you may want to only call it for the first one.
This can then be made into a function that repeats itself every 3 seconds, e.g.
(function (obj, waitFor) { // wrap to catch variables
var repeatAction = function repeatAction() { // function to be given timeout (stored in variable
obj.each(function (idx, elm) { // and named so it can reference itself; makes life easier);
var ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
elm.dispatchEvent(ev);
});
window.setTimeout(repeatAction, waitFor); // re-invocation of itself
};
window.setTimeout(repeatAction, waitFor); // initial invocation
}($('.next', $(divobj).parents(".widget")), 3000)); // passing vars
Edit: As requested, this function inserted into the code. I've also fixed syntax as best I could (there were some errors in OP's syntax) and "beautified" it.

Related

Dynamic nav menu boostrap that it is left or right side that related with sreenwidth

I have a nav menu that has got a lot ul in ul tag so I have to change where it is opened that right side or left side.
And if main menu is bigger than screenwidth then they must be hamburger menu that they are not fit on screen.
I created this js code. It is working and stable.
something that requires attention.
1- there is a class that's name is ".has-children" in my design
2- if screen bigger than 1070, it can be shown
#media (max-width: 1070px)
so You may need to change relating to your code this code in my js
if (screenWidth > 1070)
because it will be start after 1070
<script>
$(document).ready(function () {
var menu = $("#nav").find("ul:first");
var navbarSticky = $(".navbar.navbar-sticky");//navbar-sticky
var menubarLeft = $(".site-branding");//logo left
var menubarRight = $(".toolbar");//toolbar right
var right = parseInt(menubarRight.css("right").replace("px", "")); // right space of right toolbar
var oldMenu = menu.html(); //necessary for reset it that configured
var minWidthSiteMenu = 1070;
var screenWidth = $(window).outerWidth();
if (screenWidth > minWidthSiteMenu) {
menu.html(oldMenu);
setMenuPosition();
}
$(window).resize(function () {
var screenWidth = $(window).outerWidth();
if (screenWidth > minWidthSiteMenu) {
menu.html(oldMenu);
setMenuPosition();
}
});
function setMenuPosition() {
var menuFixed = false;
var humburgerMenuArray = new Array();
var counter = 0;
for (var i = 0; i < 1; i++) {
var result = navbarSticky.width() - menubarLeft.width() - menubarRight.width() - menu.width() - right - 70;// 70 for icon of humburger menu
if (result < 0) {
//console.log(menu.find("li").last().html());
humburgerMenuArray[counter] = $("#nav").find("ul:first > li:last").html();
counter++;
$("#nav").find("ul:first > li:last").remove();
result = navbarSticky.width() - menubarLeft.width() - menubarRight.width() - menu.width() - right;
menu.css("margin-left", menubarLeft.width() + result / 2 + 20 + "px");
i = -1;
menuFixed = true;
}
else {
menu.css("margin-left", menubarLeft.width() + result / 2 + 20 + "px");
i = 1;
}
//console.log(menu);
//console.log(result);
}
if (menuFixed) {
var imageHamburger = "<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-menu'><line x1='3' y1='12' x2='21' y2='12'></line><line x1='3' y1='6' x2='21' y2='6'></line><line x1='3' y1='18' x2='21' y2='18'></line></svg>";
var humburgerMenu = "<li><a href='javascript:void(0)' style='padding-top: 26px !important;' class='menu-toggle'>" + imageHamburger + "</a>";
humburgerMenu += "<ul class='sub-menu'>";
var counterHumburger = humburgerMenuArray.length;
humburgerMenuArray.forEach(function () {
var hasChildren = humburgerMenuArray[counterHumburger - 1].search("sub-menu");
if (hasChildren === -1) {
humburgerMenu += "<li>";
}
else {
humburgerMenu += "<li class='has-children'>";
}
humburgerMenu += humburgerMenuArray[counterHumburger - 1];
humburgerMenu += "</li>";
//console.log(humburgerMenuArray[counterHumburger - 1]);
counterHumburger--;
});
humburgerMenu += "</ul>";
humburgerMenu += "</li>";
menu.append(humburgerMenu);
//console.log(menu.html());
}
$("#nav").css("visibility", "visible");
//set setSubMenuPositionLeftRightSide
setSubMenuPositionLeftRightSide();
}
/* Menu Position Left or Right Side */
var style = document.createElement('style');
style.innerHTML = "li.left-arrow > a::after {border-left: 0 solid !important;border-right: .32em solid !important;}";
document.head.appendChild(style);
var menuLeftPositionIsOk = false;
var nextMenuPositon = 0;
var zIndex = 10000;
function setSubMenuPositionLeftRightSide() {
var screenWidth = $(window).outerWidth(); //outerWidth is very important because it is not contain to spage of scroll that overflow
//console.log(screenWidth);
//reset all rel attr - its name is rel-menu-position
$("#nav > ul").each(function (i) {
$(this).find("ul").removeAttr('rel-menu-position');
});
$("#nav > ul > li > ul > li").hover(function (e) {
menuLeftPositionIsOk = false;
//nextMenuPositon = 0; // it is not necessary
zIndex = 10000;
}, function (c) { });
var menuId = 0;
if (screenWidth > minWidthSiteMenu) {
$(".has-children").hover(function (e) {
zIndex++;
$(e.currentTarget).css("zIndex", zIndex);
//console.log($(e.currentTarget).css("zIndex"));
menuPositionCalculate(e, screenWidth);
},
function (c) {
menuLeftPositionIsOk = false;//this is very important for other sub menu that you have change it...
$(c.currentTarget).css("zIndex", 'auto');
$(c.currentTarget).removeClass("left-arrow");
//console.log("menu is closed");
});
}
}
function menuPositionCalculate(e, screenWidth) {
var menuPosition = $(e.target).offset().left + $(e.currentTarget).width() + $(e.currentTarget).find('ul').outerWidth();
//console.log("menuPosition " + menuPosition);
// 25px space left side
if (nextMenuPositon - $(e.currentTarget).find('ul').outerWidth() - 25 < 0) {
menuLeftPositionIsOk = false;
//console.log("RESET - left side - if " + menuPosition + " >> " + screenWidth);
}
if ($(e.currentTarget).find('ul').first().attr('rel-menu-position') === 'left') {
menuLeftPositionIsOk = true;
}
if ($(e.currentTarget).find('ul').first().attr('rel-menu-position') === 'right') {
menuLeftPositionIsOk = false;
}
// 25px space right side
if (menuPosition + 25 > screenWidth ||
menuLeftPositionIsOk ||
nextMenuPositon + 25 > screenWidth) {
menuPosition = $(e.target).offset().left + $(e.currentTarget).width() + $(e.currentTarget).find('ul').outerWidth();
menuLeftPositionIsOk = true;
nextMenuPositon = menuLeftSidePosition(e);
//console.log("left side if " + menuPosition + " >> " + screenWidth);
$(e.currentTarget).addClass("left-arrow");
$(e.currentTarget).find('ul').first().attr('rel-menu-position', 'left');
} else {
$(e.currentTarget).removeClass("left-arrow");
$(e.currentTarget).find('ul').first().attr('rel-menu-position', 'right');
}
}
function menuLeftSidePosition(e) {
//20px come over to parent menu
var menuPositionLeft = $(e.target).offset().left - $(e.currentTarget).find('ul').first().outerWidth() + 20;
$(e.currentTarget).find('ul').first().offset({ "left": menuPositionLeft });
return menuPositionLeft;
}
});
</script>

Add class to viewport Div when scrolling up and scrolling down

I use Following code to add class when elements comes into viewport and remove when it goes out of viewport
function check_if_in_view() {
var window_height = $window.height();
var window_top_position = $window.scrollTop();
var window_bottom_position = $(window).scrollTop() + $(window).height();
$.each($animation_elements, function () {
var $element = $(this);
var element_height = $element.outerHeight();
var element_top_position = $element.offset().top;
var element_bottom_position = (element_top_position + element_height);
if ((element_bottom_position <= window_bottom_position) && element_top_position >= window_top_position) {
$element.addClass('blue');
} else {
$element.removeClass('blue');
}
});
}
It works fine in scroll up and down , But now I want to add different classes for scroll up and down , I tried below code but it doesnt seem to be working .
if((element_bottom_position <= window_bottom_position)) {
$element.addClass('blue');
}
else if (element_top_position >= window_top_position) {
$element.addClass('red');
} else {
$element.removeClass('blue').removeClass('red');
}
You will have to store the value of the scrollTop outside of your function and compare the scrollTop value inside your function to check if its more of less then the initial value of scrollTop , something like THIS.
you can integrate the same in your code like so:
$(function(){
var $animation_elements = $('.justlolo'),
$window = $(window),
scrollTop = $(window).scrollTop();
function check_if_in_view() {
var window_height = $(window).height();
var window_top_position = $(window).scrollTop();
var window_bottom_position = $(window).scrollTop() + $(window).height();
$.each($animation_elements, function () {
var $element = $(this);
var element_height = $element.outerHeight();
var element_top_position = $element.offset().top;
var element_bottom_position = (element_top_position + element_height);
if ((element_bottom_position > window_top_position) && element_top_position < window_bottom_position && window_top_position > scrollTop) {
$element.removeClass('red').addClass('blue');
} else if((element_bottom_position > window_top_position) && element_top_position < window_bottom_position && window_top_position < scrollTop) {
$element.removeClass('blue').addClass('red');
} else {
$element.removeClass('blue red');
}
});
}
$(window).on('scroll' , () => {
check_if_in_view();
scrollTop = $(window).scrollTop();
})
});
*, *:after, *:before {
box-sizing: border-box;
}
.justlolo {
height: 70vh;
background: #ccc
}
div:nth-of-type(even) {
background: #eee;
opacity: 0.8;
}
.blue {
background: blue !important;
}
.red {
background: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="justlolo"></div>
<div class="justlolo"></div>
<div class="justlolo"></div>

How to add active class while scrolling in div?

Could you please tell me how to add an active class while scrolling in a div? I have one container, in which there are four divs. In the footer I also have four li (first, second, third). I want to select the li when the user scrolls the div.
Example
When the code runs, the first li should be selected because the first div is in the view port. If the user scrolls and moves to the second div, the second li should be selected. And so on.
I tried like that
https://jsbin.com/giwizufotu/edit?html,css,js,output
(function(){
'use strict';
$(function(){
$( "#container" ).scroll(function() {
console.log('scrlling');
if (elementInViewport2($('#first'))) {
// The element is visible, do something
console.log('first visible')
} else {
console.log('second visible')
}
});
})
function elementInViewport2(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
})()
I don't want to use plugin
I have tried to use almost all the code you have written with little modifications:
Here is the working example link: https://jsfiddle.net/almamun1996/21wc37sx/3/
CSS:
.item {
width:25%;
display:inline-block;
margin:0;
padding:0;
color:blue;
font-size:20px;
text-align: center;
}
.footer{
border:1px solid;
position:fixed;
width:100%;
bottom:0px;
}
#container {
border:1px solid red;
overflow:auto;
width:100%;
height:300px;
}
.fC{
background-color:yellow;
padding:0;
}
#first{
background-color:blue;
}
#second {
background-color:green;
}
#third {
background-color:pink;
}
#fourth {
background-color:red;
}
.active {
background-color : red;
}
JS:
(function(){
'use strict';
$(function(){
$('.fC li:eq(0)').css('background-color','red').css('color','#ffffff');
$( "#container" ).scroll(function() {
//console.log('scrlling');
if (elementInViewport($('#first'))) {
// The element is visible, do something
//console.log('first visible')
} else {
//console.log('second visible')
}
});
});
function elementInViewport(e) {
var winBottom = $(window).scrollTop() + $(window).height();
var visibleETop = e.offset().top - winBottom;
var first = parseInt($('#first').css('height'));
var second = parseInt($('#second').css('height'));
var third = parseInt($('#third').css('height'));
var fourth = parseInt($('#fourth').css('height'));
if(Math.abs(e.offset().top) > first - parseInt($('#container').css('height')) && Math.abs(e.offset().top) <= first+second - parseInt($('#container').css('height')))
{
$('.fC li:eq(0)').css('background-color','').css('color','');
$('.fC li:eq(2)').css('background-color','').css('color','');
$('.fC li:eq(3)').css('background-color','').css('color','');
$('.fC li:eq(1)').css('background-color','red').css('color','#ffffff');
}
else if(Math.abs(e.offset().top) > first+second - parseInt($('#container').css('height')) && Math.abs(e.offset().top) <= first+second+third - parseInt($('#container').css('height')))
{
$('.fC li:eq(0)').css('background-color','').css('color','');
$('.fC li:eq(1)').css('background-color','').css('color','');
$('.fC li:eq(3)').css('background-color','').css('color','');
$('.fC li:eq(2)').css('background-color','red').css('color','#ffffff');
}
else if(Math.abs(e.offset().top) > first+second+third - parseInt($('#container').css('height')) && Math.abs(e.offset().top) <= first+second+third+fourth - parseInt($('#container').css('height')))
{
$('.fC li:eq(0)').css('background-color','').css('color','');
$('.fC li:eq(1)').css('background-color','').css('color','');
$('.fC li:eq(2)').css('background-color','').css('color','');
$('.fC li:eq(3)').css('background-color','red').css('color','#ffffff');
}
else{
$('.fC li:eq(1)').css('background-color','').css('color','');
$('.fC li:eq(2)').css('background-color','').css('color','');
$('.fC li:eq(3)').css('background-color','').css('color','');
$('.fC li:eq(0)').css('background-color','red').css('color','#ffffff');
}
if(visibleETop < 0){
return false;
}else{
return true;
}
}
})();
HTML:
Just replace the id='three' to id='third' in third div from your html.
You should consider changing class based on one edge-
function elementInViewport(e) {
var winBottom = $(window).scrollTop() + $(window).height();
var visibleETop = e.offset().top - winBottom;
if(visibleETop < 0){
return false;
}else{
return true;
}
}

Disable jQuery function on window size

I have some jQuery that needs to activate depending on the window size.
The current code I have does trigger correctly when the page is loaded, but if I resize the window the jQuery does not enable or disable according to the size of the screen
$(document).ready(function() {
var width = $(window).width();
if ((width < 980)) {
$( '.navigation > ul > li > a' ).click(function() {
if($(this).next('ul').is(':visible')){
$(this).next("ul").slideUp(400);
} else {
$( '.navigation > ul > li > ul' ).slideUp(400);
$(this).next("ul").slideToggle(400);
}
});
$( '.navigation > ul > li > ul > li > a' ).click(function() {
if($(this).next("ul").is(":visible")){
$(this).next("ul").slideUp(400);
} else {
$( '.navigation > ul > li > ul > li > ul' ).slideUp(400);
$(this).next("ul").slideToggle(400);
}
});
$( '.menu-link' ).click(function() {
if($(this).next("div").is(':visible')){
$(this).next("div").slideUp(400);
} else {
$( '.navigation' ).slideUp(400);
$(this).next('div').slideToggle(400);
}
});
}
});
Effectively what I need is for the jQuery to trigger under a screen size of 980px and disable over that figure.
As an extra googly I need to make sure that any expanded elements are able to close or are closed when the page size exceeds 980px as over this size the usual CSS media queries take effect on hover.
An earlier version of my code was able to take into account of a dynamic window size, but left the expanded items open and unable to close since the jQuery no longer functioned.
In case it helps here's a fiddle
You need to use window.onresize method.
EDITED CODE
// flag to check that events doesn't bind twice
var isNavigationEventsEnable = false;
// enable events
var enableNavigationEvents = function () {
$(".navigation > ul > li > a").on('click.screen-lt-980', function () {
if ($(this).next("ul").is(":visible")) {
$(this).next("ul").slideUp(400);
} else {
$(".navigation > ul > li > ul").slideUp(400);
$(this).next("ul").slideToggle(400);
}
});
$(".navigation > ul > li > ul > li > a").on('click.screen-lt-980', function () {
if ($(this).next("ul").is(":visible")) {
$(this).next("ul").slideUp(400);
} else {
$(".navigation > ul > li > ul > li > ul").slideUp(400);
$(this).next("ul").slideToggle(400);
}
});
$(".menu-link").on('click.screen-lt-980', function () {
if ($(this).next("div").is(":visible")) {
$(this).next("div").slideUp(400);
} else {
$(".navigation").slideUp(400);
$(this).next("div").slideToggle(400);
}
});
}
// disable events
var disableNavigatioEvents = function () {
$(".navigation > ul > li > a").off('click.screen-lt-980');
$(".navigation > ul > li > ul > li > a").off('click.screen-lt-980');
$(".menu-link").off('click.screen-lt-980');
}
// call this method on window resize
var redesignScreen = function () {
//function (e) { // comment this line
var width = $(window).width();
if ((width < 980)) {
if (!isNavigationEventsEnable) {
isNavigationEventsEnable = true;
enableNavigationEvents();
}
} else {
isNavigationEventsEnable = false;
disableNavigatioEvents();
}
//} // comment this line
}
$(document).ready(function () {
// attach onresize function
window.onresize = redesignScreen;
// calling redesignScreen initially
redesignScreen();
});
JSFiddle: http://jsfiddle.net/hEtTg/2/
WITH FORCE CLOSE
// flag to check on that events doesn't bind twice
var isNavigationEventsEnable = false;
// enable events
var enableNavigationEvents = function () {
$(".navigation > ul > li > a").on('click.screen-lt-980', function (e, data) {
data = (typeof data == 'undefined') ? {} : data;
if ($(this).next("ul").is(":visible") || data.forceClose) {
$(this).next("ul").slideUp(400);
} else {
$(".navigation > ul > li > ul").slideUp(400);
$(this).next("ul").slideToggle(400);
}
});
$(".navigation > ul > li > ul > li > a").on('click.screen-lt-980', function (e, data) {
data = (typeof data == 'undefined') ? {} : data;
if ($(this).next("ul").is(":visible") || data.forceClose) {
$(this).next("ul").slideUp(400);
} else {
$(".navigation > ul > li > ul > li > ul").slideUp(400);
$(this).next("ul").slideToggle(400);
}
});
$(".menu-link").on('click.screen-lt-980', function (e, data) {
data = (typeof data == 'undefined') ? {} : data;
if ($(this).next("div").is(":visible") || data.forceClose) {
$(this).next("div").slideUp(400);
} else {
$(".navigation").slideUp(400);
$(this).next("div").slideToggle(400);
}
});
}
// disable events
var disableNavigatioEvents = function () {
$(".navigation > ul > li > a").trigger('click', [{
forceClose: true
}]);
$(".navigation > ul > li > ul > li > a").trigger('click', [{
forceClose: true
}]);
$(".menu-link").trigger('click', [{
forceClose: true
}]);
$(".navigation > ul > li > a").off('click.screen-lt-980');
$(".navigation > ul > li > ul > li > a").off('click.screen-lt-980');
$(".menu-link").off('click.screen-lt-980');
}
// call this method on window resize
var redesignScreen = function () {
// function (e) { // comment this line
var width = $(window).width();
if ((width < 980)) {
if (!isNavigationEventsEnable) {
isNavigationEventsEnable = true;
enableNavigationEvents();
}
} else {
isNavigationEventsEnable = false;
disableNavigatioEvents();
}
// } // comment this line
}
$(document).ready(function () {
// attach onresize function
window.onresize = redesignScreen;
// calling redesignScreen initially
redesignScreen();
});
JSFiddle:http://jsfiddle.net/hEtTg/3/
Hopes it helps.

Losing hover when animating with jQuery (without moving mouse)

I have this row of thumbnails that I am animating with jQuery.
Each of these thumbnails has a hover and active class.
They work fine but when I animate the list, the new thumbnail under the mousecursor does not apply the hover? I have to move the mouse a little bit after each click?
It's kinda difficult to exaplain.. I have made a fiddle here: http://jsfiddle.net/nZGYA/
When you start clicking after thumb 3 without moving the mouse you see what I mean...
It works fine in FireFox, NOT Safari, Chrome, IE etc.
Is there something I can do about this?
For reference here is my code:
<style type="text/css">
.container { position: relative; overflow: hidden; width: 140px; height: 460px; float: left; margin-right: 100px; background: silver; }
ul { position: absolute; top: 10; list-style: none; margin: 10px; padding: 0; }
li { margin-bottom: 10px; width: 120px; height: 80px; background: gray; }
#list-2 li a { display: block; width: 120px; height: 80px; outline: none; }
#list-2 li a:hover { background: teal; }
#list-2 li a.active { background: navy; }
</style>
$(document).ready(function() {
var idx_2 = 0;
$('#list-2 li a')
.click(function() {
$('#list-2 > li a').removeClass('active');
$(this).addClass('active');
var id = $('#list-2 li a.active').data('index') - 2;
idy = Math.max(0, id * 90);
$(this).parent().parent().animate({ 'top' : -idy + 'px' });
return false;
})
.each(function() {
$(this).data('index', idx_2);
++idx_2;
});
});
<div class="container">
<ul id="list-2">
<li><a class="active" href="#"></a></li>
<li></li><li></li><li></li><li></li>
<li></li><li></li><li></li><li></li>
<li></li><li></li><li></li><li></li>
<li></li><li></li><li></li><li></li>
<li></li><li></li><li></li><li></li>
<li></li><li></li><li></li><li></li>
</ul>
</div>
I only worked on the top list but I think I got it all working. let me know if it is what you are looking for.
Here is the fiddler
var idx = 0;
$('#list-1 li').hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
}).click
(function() {
var currentindex = $('.active').index();
var selectedindex = $(this).index();
var nexthoverindex = selectedindex + (selectedindex - currentindex);
//counter for starting on index 1
if(currentindex === 1 && selectedindex > 2){
nexthoverindex = nexthoverindex - 1;
}
//counter for starting on index 0
if(currentindex === 0 && selectedindex > 2){
nexthoverindex = nexthoverindex - 2;
}
//make sure the selection never goes below 0
if(nexthoverindex < 0){
nexthoverindex = 0;
}
$('#list-1 > li').removeClass('active');
$(this).addClass('active');
var id = $('#list-1 li.active').data('index') - 2; // take scroll param and subtract 2 to keep selected image in the middle
idy = Math.max(0, id * 90);
$(this).parent().animate({
'top': -idy + 'px'
},200, function(){
$('.hover').removeClass('hover');
if(currentindex > 2 || selectedindex > 2){
$('#list-1 > li').eq(nexthoverindex).addClass('hover');
}
});
return false;
}).css('cursor', 'pointer').each(function() {
$(this).data('index', idx);
++idx;
});
I've got a solution that works in Chrome and IE (haven't tested in Safari). Basically I trigger the mouseover() event of the element under the mouse in the animate() callback event if the thumbnails have moved. The solution is only implemented for list-1.
// list 1
var idx = 0;
$('#list-1 li').hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
}).click(function() {
$('#list-1 > li').removeClass('active');
var $active = $(this);
$active.addClass('active');
var id = $('#list-1 li.active').data('index') - 2; // take scroll param and subtract 2 to keep selected image in the middle
var moveAmount = 90;
idy = Math.max(0, id * moveAmount);
var oldPos = $active.parent().position().top;
$active.parent().animate({
'top': -idy + 'px'
}, function(){
var newPos = $(this).position().top;
// Check if we moved
if(oldPos - newPos != 0)
{
var movement = (oldPos - newPos) / moveAmount;
$($(this).children()[$active.index() + movement])
.trigger("mouseover");
}
});
return false;
}).css('cursor', 'pointer').each(function() {
$(this).data('index', idx);
++idx;
});
And here's the link to my fork in jsfiddle if you wan't to test it out over there - http://jsfiddle.net/jimmysv/3tzAt/15/

Categories

Resources