I have a jQuery Mobile carousel in my application, I need to populate data in a drop-down as soon as the carousel is flipped, this is done. Now the new implementation is that as soon as the user pauses on the carousel for >= 3 seconds then only the drop-down should be updated. So how am I suppose to capture this pause time? I am using iscroll.js
Interesting parts on the code is:
var myScroll;
var old_page=0;
function loaded() {
myScroll = new iScroll('wrapper', {
snap: true,
momentum: false,
hScrollbar: false,
onScrollEnd: function(){
var currPage = myScroll.currPageX+1;
var firstPage = parseInt(document.querySelector('#indicator > li:first-child').innerHTML);
var lastPage = parseInt(document.querySelector('#indicator > li:last-child').innerHTML);
if(currPage <= lastPage && currPage >= firstPage){
if(old_page < currPage){
document.querySelector('#indicator > li.active').className = '';
document.querySelector('#indicator > li:nth-child(' + (this.currPageX+1) + ')').className = 'active';
document.getElementById("prev").style.visibility="visible";
}
else if(old_page > currPage){
document.querySelector('#indicator > li.active').className = '';
document.querySelector('#indicator > li:nth-child(' + (this.currPageX+1) + ')').className = 'active';
document.getElementById("next").style.visibility="visible";
}
old_page = currPage;
if(old_page == lastPage ){
document.getElementById("next").style.visibility="hidden";
}
else if(old_page == firstPage ){
document.getElementById("prev").style.visibility="hidden";
}
}
else{
myScroll.scrollToPage(lastPage-1,0);
}
}
});
}
function gotoNextPage(){
if(document.getElementById("prev").style.visibility == "hidden"){
document.getElementById("prev").style.visibility="visible";
}
var currPage = parseInt(document.querySelector('#indicator > li.active').innerHTML);
var lastPage = parseInt(document.querySelector('#indicator > li:last-child').innerHTML);
if( currPage == (lastPage-1) ){
document.getElementById("next").style.visibility="hidden";
}
document.querySelector('#indicator > li.active').className = '';
document.querySelector('#indicator > li:nth-child(' + (currPage+1) + ')').className = 'active';
myScroll.scrollToPage('next', 750);
}
function gotoPrevPage(){
if(document.getElementById("next").style.visibility == "hidden"){
document.getElementById("next").style.visibility="visible";
}
var currPage = parseInt(document.querySelector('#indicator > li.active').innerHTML);
var firstPage = parseInt(document.querySelector('#indicator > li:first-child').innerHTML);
if( (currPage-1) == firstPage ){
document.getElementById("prev").style.visibility="hidden";
}
document.querySelector('#indicator > li.active').className = '';
document.querySelector('#indicator > li:nth-child(' + (currPage-1) + ')').className = 'active';
myScroll.scrollToPage('prev', 750);
}
document.addEventListener('DOMContentLoaded', loaded, false);
Tidying up and adding the additional functionality I get this :
function loaded() {
var $$ = document.querySelector;
var firstPage = parseInt($$('#indicator > li:first-child').innerHTML, 10);
var lastPage = parseInt($$('#indicator > li:last-child').innerHTML, 10);
var myScroll = new iScroll('wrapper', {
snap: true,
momentum: false,
hScrollbar: false,
onScrollEnd: function() {
var currPage = myScroll.currPageX + 1;
if(currPage <= lastPage && currPage >= firstPage) {
$$('#indicator > li.active').className = '';
$$('#indicator > li:nth-child(' + currPage + ')').className = 'active';
document.getElementById("prev").style.visibility = (currPage == firstPage) ? "hidden" : "visible";
document.getElementById("next").style.visibility = (currPage == lastPage) ? "hidden" : "visible";
}
else {
myScroll.scrollToPage(lastPage-1,0);
}
}
});
var hoverTimeout;
var wrapper = document.getElementById('wrapper');
var items = wrapper.getElementsByTagName("???");
for(var i=0; i<items.length; i++) {
var item = items[i];
item.onmouseover = function() {
var that = this;
hoverTimeout = setTimeout(function() {
updateDropdown(that);//adjust this statement to call existing function
}, 3000);
};
item.onmouseout = function() {
clearTimeout(hoverTimeout);
};
}
}
To get it working, you will need to :
in the var items = ... statement, change ??? to the tag name of the scrolled elements within the wrapper (eg 'img').
in the setTimeout(...) statement, call some existing function that update the drop-down.
EDIT
In jQuery it will be something like this :
$(function() {
var $wrapper = $('#wrapper'),
$indicatorElements = $('#indicator li'),
$prev = $("#prev"),
$next = $("#next"),
hoverTimeout;
var myScroll = new iScroll('wrapper', {
snap: true,
momentum: false,
hScrollbar: false,
onScrollEnd: function() {
var currPage = this.currPageX;
if(currPage <= ($indicatorElements.length-1) && currPage >= 0) {
$indicatorElements.removeClass('active').eq(currPage).addClass('active');
$prev.css('visibility', (currPage == 0) ? "hidden" : "visible");
$next.css('visibility', (currPage == ($indicatorElements.length-1)) ? "hidden" : "visible");
}
else {
this.scrollToPage($indicatorElements.length-1, 0);
}
}
});
$wrapper.find("img").each(function(i, item) {
$(item).hover(function() {
hoverTimeout = setTimeout(function() {
updateDropdown(item);//adjust this statement to call existing function
}, 3000);
}, function() {
clearTimeout(hoverTimeout);
};
});
});
Both version are untested and probably need debugging.
Related
I have a js pagination system that find .classname elems and paginate them on-the-fly. Clicking on navigation pages the script shows only .classname elements in that interval.
When too much items have to be paginated I would like to add an arrow system to let navigate pages links. The main script is here: https://jsfiddle.net/gyzo2u9c/
(function($) {
var pagify = {
items: {},
container: null,
totalPages: 1,
perPage: 3,
currentPage: 0,
createNavigation: function() {
this.totalPages = Math.ceil(this.items.length / this.perPage);
$('.pagination', this.container.parent()).remove();
var pagination = $('<div class="pagination"></div>').append('<a class="nav prev disabled" data-next="false"><i class="fas fa-caret-left"></i></a>');
for (var i = 0; i < this.totalPages; i++) {
var pageElClass = "page";
if (!i)
pageElClass = "page current";
var pageEl = '<a class="' + pageElClass + '" data-page="' + (
i + 1) + '">' + (
i + 1) + "</a>";
pagination.append(pageEl);
}
pagination.append('<a class="nav next" data-next="true"><i class="fas fa-caret-right"></i></a>');
/*aggiungiamo la paginazione sopra nel calendario*/
if ($(this.container).selector == '#calendario .archivio') {
this.container.before(pagination);
} else {
/*sotto, in tutti gli altri casi*/
this.container.after(pagination);
}
var that = this;
$("body").off("click", ".nav");
this.navigator = $("body").on("click", ".nav", function() {
var el = $(this);
that.navigate(el.data("next"));
});
$("body").off("click", ".page");
this.pageNavigator = $("body").on("click", ".page", function() {
var el = $(this);
that.goToPage(el.data("page"));
$([document.documentElement, document.body]).animate({
scrollTop: ($(".archivio").offset().top - 120)
}, 1);
});
},
navigate: function(next) {
// default perPage to 5
if (isNaN(next) || next === undefined) {
next = true;
}
$(".pagination .nav").removeClass("disabled");
if (next) {
this.currentPage++;
if (this.currentPage > (this.totalPages - 1))
this.currentPage = (this.totalPages - 1);
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
} else {
this.currentPage--;
if (this.currentPage < 0)
this.currentPage = 0;
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
}
this.showItems();
},
updateNavigation: function() {
var pages = $(".pagination .page");
pages.removeClass("current");
$('.pagination .page[data-page="' + (
this.currentPage + 1) + '"]').addClass("current");
},
goToPage: function(page) {
this.currentPage = page - 1;
$(".pagination .nav").removeClass("disabled");
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
this.showItems();
},
showItems: function() {
this.items.hide().removeClass('item_visibile');
var base = this.perPage * this.currentPage;
this.items.slice(base, base + this.perPage).show().addClass('item_visibile');
this.updateNavigation();
},
init: function(container, items, perPage, currentPage) {
// default perPage to 5
if (isNaN(currentPage) || currentPage === undefined) {
currentPage = 0;
}
this.container = container;
this.currentPage = currentPage;
this.totalPages = 1;
this.perPage = perPage;
this.items = items;
this.createNavigation();
this.showItems();
}
};
// stuff it all into a jQuery method!
$.fn.pagify = function(perPage, itemSelector, currentPage) {
var el = $(this);
var items = $(itemSelector, el);
// default perPage to 5
if (isNaN(perPage) || perPage === undefined) {
perPage = 3;
}
// don't fire if fewer items than perPage
if (items.length <= perPage) {
return true;
}
pagify.init(el, items, perPage, currentPage);
};
})(jQuery);
jQuery(".archive").pagify(2, ".item");
How/Where I have to add the arrow alghoritm?
Thank you in advanced
Solution:
(function($) {
var pagify = {
items: {},
container: null,
totalPages: 1,
perPage: 3,
currentPage: 0,
nextpageInterval: 20,
createNavigation: function() {
this.generateUI();
var that = this;
$("body").off("click", ".nav");
this.navigator = $("body").on("click", ".nav", function() {
var el = $(this);
that.navigate(el.data("next"));
});
$("body").off("click", ".page");
this.pageNavigator = $("body").on("click", ".page", function() {
var el = $(this);
that.goToPage(el.data("page"));
$([document.documentElement, document.body]).animate({
scrollTop: ($(".archivio").offset().top-120)
}, 1);
});
},
getPageList: function(totalPages, page, maxLength) {
if (maxLength < 5) throw "maxLength must be at least 5";
function range(start, end) {
return Array.from(Array(end - start + 1), (_, i) => i + start);
}
var sideWidth = 1;
var leftWidth = (maxLength - sideWidth*2 - 3) >> 1;
var rightWidth = (maxLength - sideWidth*2 - 2) >> 1;
if (totalPages <= maxLength) {
// no breaks in list
return range(1, totalPages);
}
if (page <= maxLength - sideWidth - 1 - rightWidth) {
// no break on left of page
return range(1, maxLength - sideWidth - 1)
.concat(0, range(totalPages - sideWidth + 1, totalPages));
}
if (page >= totalPages - sideWidth - 1 - rightWidth) {
// no break on right of page
return range(1, sideWidth)
.concat(0, range(totalPages - sideWidth - 1 - rightWidth - leftWidth, totalPages));
}
// Breaks on both sides
return range(1, sideWidth)
.concat(0, range(page - leftWidth, page + rightWidth),
0, range(totalPages - sideWidth + 1, totalPages));
},
generateUI: function(){
this.totalPages = Math.ceil(this.items.length / this.perPage);
var pages = this.getPageList(this.totalPages, this.currentPage, this.nextpageInterval);
$('.pagination', this.container.parent()).remove();
var pagination = $('<div class="pagination"></div>');
for (var i = 0; i < pages.length; i++) {
var pageElClass = "page";
if (pages[i] == (this.currentPage + 1)){
pageElClass = "page current";
}
if(pages[i] != 0){
var lbl = pages[i];
if(i == 0 && pages[i + 1] == 0){
lbl = '<i class="fas fa-step-backward"></i>';
}else if(i == (pages.length-1) && pages[i - 1] == 0){
lbl = '<i class="fas fa-step-forward"></i>';
}
var pageEl = '<a class="' + pageElClass + '" data-page="' + (
pages[i]) + '">' + (
lbl) + "</a>";
pagination.append(pageEl);
}else{
if(i == 1){
var prevEl = '<a class="nav prev disabled" data-next="false"><i class="fas fa-caret-left"></i></a>';
pagination.append(prevEl);
}else{
var nextEl = '<a class="nav next" data-next="true"><i class="fas fa-caret-right"></i></a>';
pagination.append(nextEl);
}
}
}
/*aggiungiamo la paginazione sopra nel calendario*/
if ($(this.container).selector == '#calendario .archivio'){
this.container.before(pagination);
} else {
/*sotto, in tutti gli altri casi*/
this.container.after(pagination);
}
},
navigate: function(next) {
// default perPage to 5
if (isNaN(next) || next === undefined) {
next = true;
}
$(".pagination .nav").removeClass("disabled");
if (next) {
this.currentPage++;
if (this.currentPage > (this.totalPages - 1))
this.currentPage = (this.totalPages - 1);
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
}
else {
this.currentPage--;
if (this.currentPage < 0)
this.currentPage = 0;
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
}
this.showItems();
},
updateNavigation: function() {
var pages = $(".pagination .page");
pages.removeClass("current");
$('.pagination .page[data-page="' + (
this.currentPage + 1) + '"]').addClass("current");
this.generateUI();
},
goToPage: function(page) {
this.currentPage = page - 1;
$(".pagination .nav").removeClass("disabled");
if (this.currentPage == (this.totalPages - 1))
$(".pagination .nav.next").addClass("disabled");
if (this.currentPage == 0)
$(".pagination .nav.prev").addClass("disabled");
this.showItems();
},
showItems: function() {
this.items.hide().removeClass('item_visibile');
var base = this.perPage * this.currentPage;
this.items.slice(base, base + this.perPage).show().addClass('item_visibile');
this.updateNavigation();
},
init: function(container, items, perPage, currentPage) {
// default perPage to 5
if (isNaN(currentPage) || currentPage === undefined) {
currentPage = 0;
}
this.container = container;
this.currentPage = currentPage;
this.totalPages = 1;
this.perPage = perPage;
this.items = items;
this.createNavigation();
this.showItems();
}
};
// stuff it all into a jQuery method!
$.fn.pagify = function(perPage, itemSelector, currentPage) {
var el = $(this);
var items = $(itemSelector, el);
// default perPage to 5
if (isNaN(perPage) || perPage === undefined) {
perPage = 3;
}
// don't fire if fewer items than perPage
if (items.length <= perPage) {
return true;
}
pagify.init(el, items, perPage, currentPage);
};
})(jQuery);
I am using a template with the following code to handle scrolling:
Here is the template.
This is the javascript code for scrolling, I can post the html and css if needed but it is large.
// #codekit-prepend "/vendor/hammer-2.0.8.js";
$( document ).ready(function() {
// DOMMouseScroll included for firefox support
var canScroll = true,
scrollController = null;
$(this).on('mousewheel DOMMouseScroll', function(e){
if (!($('.outer-nav').hasClass('is-vis'))) {
e.preventDefault();
var delta = (e.originalEvent.wheelDelta) ? -e.originalEvent.wheelDelta : e.originalEvent.detail * 20;
if (delta > 50 && canScroll) {
canScroll = false;
clearTimeout(scrollController);
scrollController = setTimeout(function(){
canScroll = true;
}, 800);
updateHelper(1);
}
else if (delta < -50 && canScroll) {
canScroll = false;
clearTimeout(scrollController);
scrollController = setTimeout(function(){
canScroll = true;
}, 800);
updateHelper(-1);
}
}
});
$('.side-nav li, .outer-nav li').click(function(){
if (!($(this).hasClass('is-active'))) {
var $this = $(this),
curActive = $this.parent().find('.is-active'),
curPos = $this.parent().children().index(curActive),
nextPos = $this.parent().children().index($this),
lastItem = $(this).parent().children().length - 1;
updateNavs(nextPos);
updateContent(curPos, nextPos, lastItem);
}
});
$('.cta').click(function(){
var curActive = $('.side-nav').find('.is-active'),
curPos = $('.side-nav').children().index(curActive),
lastItem = $('.side-nav').children().length - 1,
nextPos = lastItem;
updateNavs(lastItem);
updateContent(curPos, nextPos, lastItem);
});
// swipe support for touch devices
var targetElement = document.getElementById('viewport'),
mc = new Hammer(targetElement);
mc.get('swipe').set({ direction: Hammer.DIRECTION_VERTICAL });
mc.on('swipeup swipedown', function(e) {
updateHelper(e);
});
$(document).keyup(function(e){
if (!($('.outer-nav').hasClass('is-vis'))) {
e.preventDefault();
updateHelper(e);
}
});
// determine scroll, swipe, and arrow key direction
function updateHelper(param) {
var curActive = $('.side-nav').find('.is-active'),
curPos = $('.side-nav').children().index(curActive),
lastItem = $('.side-nav').children().length - 1,
nextPos = 0;
if (param.type === "swipeup" || param.keyCode === 40 || param > 0) {
if (curPos !== lastItem) {
nextPos = curPos + 1;
updateNavs(nextPos);
updateContent(curPos, nextPos, lastItem);
}
else {
updateNavs(nextPos);
updateContent(curPos, nextPos, lastItem);
}
}
else if (param.type === "swipedown" || param.keyCode === 38 || param < 0){
if (curPos !== 0){
nextPos = curPos - 1;
updateNavs(nextPos);
updateContent(curPos, nextPos, lastItem);
}
else {
nextPos = lastItem;
updateNavs(nextPos);
updateContent(curPos, nextPos, lastItem);
}
}
}
// sync side and outer navigations
function updateNavs(nextPos) {
$('.side-nav, .outer-nav').children().removeClass('is-active');
$('.side-nav').children().eq(nextPos).addClass('is-active');
$('.outer-nav').children().eq(nextPos).addClass('is-active');
}
// update main content area
function updateContent(curPos, nextPos, lastItem) {
$('.main-content').children().removeClass('section--is-active');
$('.main-content').children().eq(nextPos).addClass('section--is-active');
$('.main-content .section').children().removeClass('section--next section--prev');
if (curPos === lastItem && nextPos === 0 || curPos === 0 && nextPos === lastItem) {
$('.main-content .section').children().removeClass('section--next section--prev');
}
else if (curPos < nextPos) {
$('.main-content').children().eq(curPos).children().addClass('section--next');
}
else {
$('.main-content').children().eq(curPos).children().addClass('section--prev');
}
if (nextPos !== 0 && nextPos !== lastItem) {
$('.header--cta').addClass('is-active');
}
else {
$('.header--cta').removeClass('is-active');
}
}
function workSlider() {
$('.slider--prev, .slider--next').click(function() {
var $this = $(this),
curLeft = $('.slider').find('.slider--item-left'),
curLeftPos = $('.slider').children().index(curLeft),
curCenter = $('.slider').find('.slider--item-center'),
curCenterPos = $('.slider').children().index(curCenter),
curRight = $('.slider').find('.slider--item-right'),
curRightPos = $('.slider').children().index(curRight),
totalWorks = $('.slider').children().length,
$left = $('.slider--item-left'),
$center = $('.slider--item-center'),
$right = $('.slider--item-right'),
$item = $('.slider--item');
$('.slider').animate({ opacity : 0 }, 400);
setTimeout(function(){
if ($this.hasClass('slider--next')) {
if (curLeftPos < totalWorks - 1 && curCenterPos < totalWorks - 1 && curRightPos < totalWorks - 1) {
$left.removeClass('slider--item-left').next().addClass('slider--item-left');
$center.removeClass('slider--item-center').next().addClass('slider--item-center');
$right.removeClass('slider--item-right').next().addClass('slider--item-right');
}
else {
if (curLeftPos === totalWorks - 1) {
$item.removeClass('slider--item-left').first().addClass('slider--item-left');
$center.removeClass('slider--item-center').next().addClass('slider--item-center');
$right.removeClass('slider--item-right').next().addClass('slider--item-right');
}
else if (curCenterPos === totalWorks - 1) {
$left.removeClass('slider--item-left').next().addClass('slider--item-left');
$item.removeClass('slider--item-center').first().addClass('slider--item-center');
$right.removeClass('slider--item-right').next().addClass('slider--item-right');
}
else {
$left.removeClass('slider--item-left').next().addClass('slider--item-left');
$center.removeClass('slider--item-center').next().addClass('slider--item-center');
$item.removeClass('slider--item-right').first().addClass('slider--item-right');
}
}
}
else {
if (curLeftPos !== 0 && curCenterPos !== 0 && curRightPos !== 0) {
$left.removeClass('slider--item-left').prev().addClass('slider--item-left');
$center.removeClass('slider--item-center').prev().addClass('slider--item-center');
$right.removeClass('slider--item-right').prev().addClass('slider--item-right');
}
else {
if (curLeftPos === 0) {
$item.removeClass('slider--item-left').last().addClass('slider--item-left');
$center.removeClass('slider--item-center').prev().addClass('slider--item-center');
$right.removeClass('slider--item-right').prev().addClass('slider--item-right');
}
else if (curCenterPos === 0) {
$left.removeClass('slider--item-left').prev().addClass('slider--item-left');
$item.removeClass('slider--item-center').last().addClass('slider--item-center');
$right.removeClass('slider--item-right').prev().addClass('slider--item-right');
}
else {
$left.removeClass('slider--item-left').prev().addClass('slider--item-left');
$center.removeClass('slider--item-center').prev().addClass('slider--item-center');
$item.removeClass('slider--item-right').last().addClass('slider--item-right');
}
}
}
}, 400);
$('.slider').animate({ opacity : 1 }, 400);
});
}
function transitionLabels() {
$('.work-request--information input').focusout(function(){
var textVal = $(this).val();
if (textVal === "") {
$(this).removeClass('has-value');
}
else {
$(this).addClass('has-value');
}
// correct mobile device window position
window.scrollTo(0, 0);
});
}
outerNav();
workSlider();
transitionLabels();
});
How can I disable this code so the background doesn't scroll when an elements display is set to "block" meaning a modal is present?
Sorry for being vague if you need more specifics let me know!
EDIT 1:
I have tried disabled the div using:
$(".l-viewport").attr('disabled','disabled');
I have set the z-index of the model above all else
you can create a class HideScroll in your css:
.HideScroll {
overflow-y: hidden !important;
overflow-x: hidden !important;
}
The in the code that displays your modal, add this css to your main div:
$('.yourMainDivClass').addClass('HideScroll')
upon modal close, remove the class:
$('.yourMainDivClass').removeClass('HideScroll')
you can also use jquery toggleClass function.
OR
you can wrap your main div inside <fieldset> and set it's disabled attribute to true:
<fieldset id="fs-1">
<div id="yourMainDiv"></div>
</fieldset>
upon showing modal:
$('#fs-1').attr('disabled', true);
upon closing modal:
$('#fs-1').removeAttr('disabled');
I wrote a basic slider in Javascript in a practice file and now trying to implement it in my site by converting it to jQuery for efficiency, however with using jQuery it doesn't work. I don't see where I am wrong.
JavaScript
(function Slider() {
var slide = document.getElementsByClassName("slide"),
dot = document.getElementsByClassName("dot"),
slideList = [slide[0],slide[1],slide[2]],
buttonL = document.getElementById('btL'),
buttonR = document.getElementById('btR'),
index = 0;
slideList[0].style.display = 'block';
(function displayDot() {
var dotContainer = document.getElementById('dotContainer'),
dotHtml ='',
i;
for (i = 0; i < slideList.length; i++) {
dotHtml += '<div class="dot"></div>';
}
dotContainer.innerHTML = dotHtml;
}());
dot[0].style.backgroundColor = '#e29f6f';
function slideIt(direction) {
previous = index;
if (direction === 'right') {
index++;
if (index >= slideList.length) {
index = 0;
}
} else if (direction === 'left') {
index--;
if (index < 0) {
index = slideList.length-1;
}
}
slideList[index].style.display = 'block';
slideList[previous].style.display = 'none';
dot[index].style.backgroundColor = '#e29f6f';
dot[previous].style.backgroundColor = 'grey';
}
buttonR.addEventListener('click', function(){ slideIt('right'); }, false);
buttonL.addEventListener('click', function(){ slideIt('left'); }, false);
}());
jQuery attempt
$(document).ready(function() {
var slide = $( ".slide" ),
dot = $( ".dot" ),
slideList = [slide[0], slide[1], slide[2]],
buttonL = $( '#btL' ),
buttonR = $( '#btR' ),
index = 0;
slideList[0].css("display", "block");
(function displayDots() {
var dotContainer = $( "#dotContainer" ),
dotHtml ='',
i;
for (i = 0; i < slideList.length; i++) {
dotHtml += '<div class="dot"></div>';
}
dotContainer.append(dotHtml);
}());
dot[0].css("background-color", "#e29f6f");
function slideIt(direction) {
previous = index;
if (direction === 'right') {
index++;
if (index >= slideList.length) {
index = 0;
}
} else if (direction === 'left') {
index--;
if (index < 0) {
index = slideList.length-1;
}
}
slideList[index].css("display", "block");
slideList[previous].css("display", "none");
dot[index].css("background-color", "#e29f6f");
dot[previous].css("background-color", "grey");
}
buttonL.click(function() {
slideIt('left');
});
buttonR.click(function() {
slideIt('right');
});
});
when you do something like:
$( ".dot" )
You can do:
$( ".dot" ).css(...);
The result is a JQuery collection
But no
$( ".dot" )[0].css(...);
$( ".dot" )[0] is a DOM node
You can do for example:
var elem = $( ".dot" )[0];
$(elem).css(...);
I'm currently building a small slider in Javascript
which is working pretty well (almost) but I have an issue !
You will find here the codepen link :
Slider
Line 22, 32, 38
I have my two navigations supposed to add a class active (after remove) but I have a shift with my next/prev button and the other buttons below the slider. I can't find a solution and it's a pain :( !
Any idea ? Thank you !
Try to use this your changed code:
var currentSlide = 0;
var prevSlide = 0;
var slider = document.getElementById('slider').children[0];
var slides = document.getElementsByClassName('slider-item');
var links = document.getElementsByClassName('link');
var prev = document.querySelector('.prev');
var next = document.querySelector('.next');
var btnActive = document.getElementsByClassName('set-active');
for (var i = 0; i < slides.length; i++) {
slider.style.width = (slides[0].clientWidth * slides.length) + 'px';
links[i].innerHTML = i + 1;
links[i].addEventListener('click', function(e) {
e.preventDefault();
prevSlide = currentSlide;
currentSlide = this.getAttribute('data-href');
slider.style.left = '-' + (100 * currentSlide) + '%';
utils.addClass(links[currentSlide], 'active');
utils.removeClass(links[prevSlide], 'active');
});
}
function updateSlide() {
slider.style.left = '-' + (100 * currentSlide) + '%';
utils.addClass(links[currentSlide], 'active');
utils.removeClass(links[prevSlide], 'active');
}
prev.addEventListener('click', function() {
if(currentSlide == 0)
return
prevSlide = currentSlide;
currentSlide--;
updateSlide();
});
next.addEventListener('click', function() {
if(currentSlide == 10)
return
prevSlide = currentSlide;
currentSlide++;
updateSlide();
});
var utils = utils || (function() {
'use strict';
return {
hasClass: function(el, cl) {
var regex = new RegExp('(?:\\s|^)' + cl + '(?:\\s|$)');
return !!el.className.match(regex);
},
addClass: function(el, cl) {
el.className += ' ' + cl;
},
removeClass: function(el, cl) {
var regex = new RegExp('(?:\\s|^)' + cl + '(?:\\s|$)');
el.className = el.className.replace(regex, ' ');
},
toggleClass: function(el, cl) {
var testClass = this.hasClass(el, cl) ? this.removeClass(el, cl) : this.addClass(el, cl);
},
getNextElementSibling: function(el) {
if (el.nextElementSibling) {
return el.nextElementSibling;
} else {
do {
el = el.nextSibling;
}
while (el && el.nodeType !== 1);
return el;
}
},
elementInViewport: function(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 && rect.left >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight)
);
},
sameHeight: function(el) {
var maxHeight = 0;
for (var i = 0; i < el.length; i++) {
var thisHeight = el[i].offsetHeight;
if (thisHeight > maxHeight) {
maxHeight = thisHeight;
}
}
for (i = 0; i < el.length; i++) {
el[i].style.height = maxHeight + 'px';
}
}
};
})();
Here is my code:
var $cur = 0;
$(document).ready(function (e) {
$tot = document.getElementsByTagName("img").length;
changetile();
});
function changetile() {
if ($cur == $tot) {
$next = 1;
} else {
$next = $cur + 1;
}
$("#tile-" + $cur).fadeOut(1000);
$("#tile-" + $next).fadeIn(1000);
$cur = $next;
}
var myVar = setInterval(function () {
changetile()
}, 4500);
This code does not work in Chrome (it works the first time). What can I do to fix it?
$tot has local scope can not be accessible outside the block.
DOM ready($(document).ready(function(){) has a anonymous function so your$tot variable has local scope
Move all your code inside DOM Ready
var $cur = 0;
$(document).ready(function (e) {
$tot = document.getElementsByTagName("img").length;
function changetile() {
if ($cur == $tot) {
$next = 1;
} else {
$next = $cur + 1;
}
$("#tile-" + $cur).fadeOut(1000);
$("#tile-" + $next).fadeIn(1000);
$cur = $next;
}
var myVar = setInterval(function () {
changetile()
}, 4500);
changetile();
});
Read What is the scope of variables in JavaScript?
var $cur = 0;
$(document).ready(function (e) {
var myVar = setInterval(function () {
$tot = document.getElementsByTagName("img").length;
changetile()
}, 4500);
});
function changetile() {
if ($cur == $tot) {
$next = 1;
} else {
$next = $cur + 1;
}
$("#tile-" + $cur).fadeOut(1000);
$("#tile-" + $next).fadeIn(1000);
$cur = $next;
}
Change your code like this. It will work
Your Code is Works in my Browser( Chrome ) :
But for you its not , then you should try With this :
var $cur = 0,$tot;
$(document).ready(function (e) {
$tot = document.getElementsByTagName("img").length;
var myVar = setInterval(changetile,4500);
});
function changetile() {
if ($cur == $tot) {
$next = 1;
} else {
$next = $cur + 1;
}
$("#tile-" + $cur).fadeOut(1000);
$("#tile-" + $next).fadeIn(1000);
$cur = $next;
}
It isn't an issue with Chrome - it's an issue with your code. Here is the output I got:
First Iteration
Cur != tot! VM325:14
Cur = 0 $tot = 9 VM325:16
Next val is : 1 VM325:17
Second Iteration:
Cur != tot! VM325:14
Cur = 1 $tot = 9 VM325:16
Next val is : 2 VM325:17
Thrid:
Cur != tot! VM325:14
Cur = 2 $tot = 9 VM325:16
Next val is : 3 VM325:17
etc.
I got this by simply putting some console.log statements in there to see what's going on:
$(document).ready(function (e) {
$tot = document.getElementsByTagName("img").length;
changetile();
});
function changetile() {
if ($cur == $tot) {
$next = 1;
console.log(" Cur == tot! ");
} else {
$next = $cur + 1;
console.log(" Cur != tot! ");
}
console.log( "Cur = " + $cur + " $tot = " + $tot );
console.log( " Next val is : " + $next )
$cur = $next;
}
var myVar = setInterval(changetile, 4500);
Edit: #tushar-gupta gives ya the answer =] I just point you in the direction ( in case you just needed a pointer )