Converting Javascript to jQuery not working - javascript

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(...);

Related

Vanilla Javascript animate margin-left of section

I'm having an issue getting my slider to work. It's a simple system of clicking buttons to get to and from sections but I'm having issues getting it to work.
I have made a codepen here: https://codepen.io/ItsBrianAgar/pen/JrbZEz
This is the js I have so far.
It needs to be Vanilla Js
var nextSection = function() {
var username = document.querySelector("input[name=\"username\"]").value;
var password = document.querySelector("input[name=\"password\"]").value;
if (username.length && password.length > 4) {
return window.location = "appSection.html";
} else {
alert("username and password must be longer than 4 characters");
}
}
var nextPage = function() {
var elem = document.getElementsByClassName("app");
var pos = 0;
var posDiff = 0;
var currentPos = elem[1].style.marginLeft;
var id = setInterval(frame, 5);
function frame() {
if (posDiff == -320) {
clearInterval(id);
posDiff = 0;
} else {
pos--;
for (var i = 0; i < elem.length; i++) {
elem[i].style.marginLeft = pos + 'px';
}
posDiff = currentPos + pos;
}
}
}
document.getElementById("cancel").onclick = previousPage = function() {
var elem = document.getElementsByClassName("app");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
for (var i = 0; i < elem.length; i++) {
if (pos == 640) {
clearInterval(id);
} else {
elem[i].style.marginLeft = pos + 'px';
pos += 320;
}
}
}
}
You can use Element.animate() to animate a DOM element
const [div, animationState, props] = [
document.querySelector("div")
, ["click to animate", "click to reverse animation"]
, ["0px", "320px"] // from, to
];
div.textContent = animationState[0];
div.onclick = () => {
div.animate({
marginLeft: props
}, {
duration: 1000,
easing: "linear",
iterations: 1,
fill: "both"
})
.onfinish = function() {
props.reverse();
div.textContent = animationState.reverse()[0];
}
}
<div></div>

how to select elements by tag name only within a specified div

I am trying to make a simple slide show to cycle through my images. The problem I'm having is when trying to select only the images in the "image_wrapper" div using document.getElementById("image_wrapper").getElementsByTagName("img")
is that it also selects the images from a sibling div. I only want to cycle through the images in the image_wrapper div.
The html onclick calls addOne() when the right arrow is clicked, and takeOne() when the left arrow is clicked
var x = 0;
var hideImage = document.getElementsByClassName("profile_image");
function displayOne() {
for(i = 0; i < hideImage.length; i++) {
if(i == 0) {
hideImage[0].style.display = "inline-block";
}
}
}
function addOne() {
var profileImg = document.getElementById("image_wrapper").getElementsByTagName("img");
if(x < profileImg.length ) {
x++;
} else {
x = 0;
}
for(i = 0; i < profileImg.length ; i++) {
if(x == profileImg.length) { x = 0;}
if(x == i) {
profileImg[i].style.display = "inline-block";
} else {
profileImg[i].style.display = "none";
}
}
}
function takeOne() {
var profileImg = document.getElementById("image_wrapper").getElementsByTagName("img");
if(x > 0 ) {
x--;
} else {
x += profileImg.length - 1 ;
}
for(i = 0; i < profileImg.length ; i++) {
if(x == -1) { x = profileImg.length; }
if(x == i) {
profileImg[i].style.display = "inline-block";
} else {
profileImg[i].style.display = "none";
}
}
}
Have you tried;
document.querySelectorAll('#image_wrapper img');
document.querySelectorAll() and document.querySelector() can take css selectors.

Resolve conflict with navigation slider in javascript

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';
}
}
};
})();

Too much recursion Error in jQuery-1.7.2,is jquery error?

too much recursion error occur when i execute autocomplete.js today.Before today i never see like this error in jquery when i execute autocomplete.js. i am using jQuery 1.7.2
$(function(){
$("#search_text").keyup(function(e){
var sVal = $(this).val();
if(e.which == 27) {
$('#sresult_container').remove();
return;
}
if(e.which != 40 && e.which != 38) {
$("#search").removeAttr('disabled');
$.post('http://localhost/website/index.php/search/ajaxResults',{Search:sVal},function(data){
if(data != "$$$" && data.length != 0) {
var sData = data;
var flag1 = 0;
var flag2 = 0;
var tabindex = -1;
var aFarray = sData.split('$$$');
$('#sresult_container').remove();
var $sresult_container = $('<div id="sresult_container"></div>')
.css({'position':'absolute','border':'1px solid','background-color':'white','z-index':'10000000','width':'309px'});
for(var i=0;i<aFarray.length;i++) {
var a = aFarray[i].split('|||');
if(i == 0 && a[0] != "") {
flag1 = 1;
$pages = $('<div id="pages"></div>');
$text1 = $('<p></p>').css({'background-color':'silver','text-align':'center','padding':'3px'}).text("Pages");
$pages.append($text1);
if(a.length > 5) {
a = a.slice(0,5);
}
for(var j=1;j<a.length+1;j++) {
tabindex++;
$('<div>/div>').css({'padding':'5px','text-align':'center'}).text(a[j-1]).attr({'tabindex':tabindex,'class':'result'}).appendTo($pages);
}
}
if(i == 1 && a[0] != "") {
flag2 = 1;
$articles = $('<div id="articles"></div>');
$text2 = $("<p></p>").css({'background-color':'silver','text-align':'center','padding':'3px'}).text("Articles");
$articles.append($text2);
if(a.length > 5) {
a = a.slice(0,5);
}
for(var j=0;j<a.length;j++) {
tabindex++;
$('<div></div>').css({'padding':'5px','text-align':'center'}).text(a[j]).attr({'tabindex':tabindex,'class':'result'}).appendTo($articles);
}
}
}
if(flag1 == 0)
{
$articles.children().first().remove();
$div = $sresult_container.append($articles);
}else if(flag2 == 0)
{
$pages.children().first().remove();
$div = $sresult_container.append($pages);
}else
{
$div = $sresult_container.append($pages,$articles);
}
tabindex++;
$allresluts = $('<div id="allresults"></div>').css({'padding':'5px','text-align':'center','background-color':'#FBEE92','color':'#CC3333'}).text("See All Results").attr('tabindex',tabindex).appendTo($div);
var bottom = $('#search_text').offset();
var height = $('#search_text').outerHeight();
var left = bottom.left;
var top = bottom.top+height;
$div.offset({'top':top,'left':left});
$('body').append($div);
}
else
{
$('#sresult_container').remove();
$("#search").attr('disabled','true');
}
});
}
else
{
$con_div = $('#sresult_container').children().children('div').add($('#sresult_container').children().last());
var tabindex = $con_div.length - 1;
if(e.which == 40)
{
$con_div.first().addClass("selected").focus();
var index = $con_div.first().index(this)+1;
$con_div.bind({
keydown: function(e) {
e.preventDefault();
var key = e.keyCode;
var target = $(e.target);
switch(key) {
case 38: // arrow up
if(index == 0)
{
index = tabindex+1;
}
$con_div[--index].focus();
break;
case 40: // arrow down
if(index > tabindex-1)
{
index = -1;
}
$con_div[++index].focus();
break;
case 13: //Enter
if(target.hasClass('result') == true)
{
$("#search_text").val(target.text());
$("#search").focus();
}
else
{
$('#search').click();
}
$div.remove();
break;
case 27://Esc
$div.remove();
$("#search_text").focus();
break;
}
},
focusin: function(e) {
$(e.currentTarget).addClass("selected");
},
focusout: function(e) {
$con_div.removeClass("selected");
$(e.currentTarget).removeClass("selected");
}
});
}
}
setTimeout(function()
{
$con_div = $('#sresult_container').children().children('div').add($('#sresult_container').children().last());
$con_div.live({
click : function(e){
var $target = $(e.target);
if($target.hasClass('result') == true)
{
$("#search_text").val($target.text());
$("#search").focus();
}
else
{
$('#search').click();
}
$('#sresult_container').remove();
},
mouseover : function(e){
var $target = $(e.target);
if($target.hasClass('result') == true || $target.is('#allresults'))
{
$(e.target).css('cursor','pointer');
$con_div.removeClass("selected");
$(e.target).addClass("selected");
}
},
mouseout : function(){
$con_div.removeClass("selected");
}
});
}, 200 );
});
$("#search_text").blur(function(e){
$con_div = $('#sresult_container').children().children('div').add($('#sresult_container').children().last());
if($con_div.hasClass('selected') != true)
{
$("#sresult_container").remove();
}
});
});
I got error in $('#search').click(); inside the code.

How to capturing the pause time in jQuery Mobile carousel?

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.

Categories