I'm having some problems, I'd like to have a sort of slideshow where users have 4 buttons, and when they click one div appears and the others disappear. The div's are all in the same place with the same size. I'd also like to put this automatic
var Idx = 1;
var IntervalKey = setInterval = (auto, 5000);
var auto = function() {
$("#MainImage").eq(Idx).fadeIn(1000);
while(Idx <3) {
Idx++;
$("#MainImage").eq(Idx).hide();
}
Idx++;
if(Idx>3) {
Idx = 0;
}
};
$(".botao-imagem").click(function(){
Idx = $(".botao-imagem").index(this);
auto();
});
Your main issue is repeated IDs, IDs must be unique, so $("#ID").eq() doesn't every have a purpose really, since it should be 1 or 0 results. First give the elements a class instead:
<div class="MainImage"><p>111111</p></div>
<div class="MainImage"><p>222222</p></div>
<div class="MainImage"><p>333333</p></div>
<div class="MainImage"><p>444444</p></div>
and use a class selector, like this:
$(".MainImage")
Also auto needs to be declared before using it or define it as a function directly, overall like this:
var Idx = 0;
var IntervalKey = setInterval(auto, 5000);
function auto() {
$(".MainImage").hide().eq(Idx).fadeIn(1000);
Idx++;
if(Idx>3) Idx = 0;
};
$(".botao-imagem").click(function(){
Idx = $(".botao-imagem").index(this);
auto();
});
You can test the updated/working version with the above code here.
Related
i've been trying to create an effect like a string is being typed in my webpage. In other words that string will appear character by character. so I did this using jquery and succeded .
the code I used is something like this,
$(function() {
var string = "Coming Soon|",
stringCount = 0;
setInterval(function(){
$('.main_section_animate span').append(string[stringCount]);
stringCount += 1;
},100);
})
Note that the span tag is empty, nothing is in there.
Problem is now I'm trying to delete the string character by character, backwards. I've tried using setInterval and replace(string[stringCount],''), selecting the main section span and main section span.text() but it didn't work and gave some weird results.
And also there are other thing I tried but mainly some combinition of text() with replace
so, anyone can help me out with this?
can be:
let str = 'Coming Soon |';
const $span = $('.main_section_animate span');
$span.html(str);
const animation = setInterval(() => {
str = str.slice(0, -1)
$span.html(str)
!str.length && clearInterval(animation)
}, 100)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main_section_animate">
<span></span>
</div>
You should probably clear that interval to get the intended result, see: https://jsfiddle.net/2mj5zp7h/
HTML:
<div class="main_section_animate">
<span></span>
</div>
JS:
$(function() {
var string = "Coming Soon|",
stringCount = 0;
var animation = setInterval(function(){
$('.main_section_animate span').append(string[stringCount]);
stringCount += 1;
if(stringCount>=string.length) {
clearInterval(animation);
animation = setInterval(function(){
$('.main_section_animate span').text(string.substr(0,stringCount));
stringCount -=1;
if(stringCount<0)
clearInterval(animation);
},100);
}
},100);
})
EDITED: Change code.
This is a solution for you :)
Use split();
const str = "Coming Soon ...";
let timer;
function deletingEffect() {
let word = str.split("");
var loopDeleting = function() {
word.pop();
document.getElementById('word').innerHTML = word.join("");
timer = setTimeout(loopDeleting, 200);
};
loopDeleting();
};
deletingEffect();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main_section_animate">
<span id="word"></span>
</div>
Use .slice() and a simple for loop to get what you need.
let str = 'Coming Soon|';
for (let i = -1+str.length; i > 0; i--) {
let delay = 100*(str.length-(i+1))
setTimeout(()=>{
$('.main_section_animate span').html( str.slice(0, i) );
}, delay);
}
Notice the for loop starts at .length and walks downwards (i--) while i > 0. This gives you an easy way to use str.slice().
Also notice the removal of setInterval which is a waste of CPU in your case. Instead, just set a one-shot setTimeout for each removal.
Finally, use .html instead of .append.
There is a simple Slider Effect below, but I have some question with it:
it's work
$(function () {
var slideIndex = 1;
SliderShow(slideIndex);
function plusIndex(n) {
SliderShow(slideIndex += n);
}
function SliderShow(n) {
var Slider = $('.Slider');
var SliderItem = Slider.children('li');
if (n > SliderItem.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = SliderItem.length;
}
for (var i = 0; i < SliderItem.length; i++) {
SliderItem[i].style.display = "none";
}
SliderItem[slideIndex - 1].style.display = "block";
}
$('.prevBtn').click(function () {
plusIndex(-1);
});
$('.nextBtn').click(function () {
plusIndex(+1);
});
});
but when I change SliderItem[i].style.display = "none" to SliderItem[i].hide() the slide was broken, what's wrong with it?
There is any different between Jquery hide and js style?
Did I misunderstand sometihing?
Because this SliderItem[slideIndex-1] returns a native DOM element which does not have a hide method, you need to wrap it with jQuery function $:
$(SliderItem[slideIndex-1]).hide();
To answer your first question "difference between jquery hide and js style"
The behaviour of these two are most likely the same except for one thing.
By using SliderItem[i].style.display = "none"
You are only changing the style display to none
While JQuery .hide() does an extra stuff which is saving the previous value of display property to cache so you can get back to it later when you use .show().
You may check this link as reference.
I'm using a function on my website to randomly addClass to a div.
works fine, but I can't find a way to not repeat the same class twice one after the other (cause sometimes the same class is added and we can think the code is not working)...
here is my jquery code :
$("#switch").click(function(){
var classes = ["vert", "escalier","reverse","demi_escalier","demi_escalier_2","ligne" ];
$("#logo").removeClass().addClass(classes[~~(Math.random()*classes.length)]);
});
can anybody help me with this ?
thanks
if you want classes not repeat you can use following:
var classes = ["vert", "escalier", "reverse", "demi_escalier", "demi_escalier_2", "ligne"];
var classesCopy = classes.slice();
$('#switch').click(function() {
if (!classesCopy.length) {
classesCopy = classes.slice();
} // once alls classes used up it starts from beginning
var classToAdd = classesCopy.splice(Math.floor(Math.random() * classesCopy.length), 1);
$('.current-class').text('current class: ' + classToAdd);
$('#logo').removeClass().addClass(classToAdd+'');
});
#logo {
width: 100px;
height: 100px;
background: green;
}
<div class='current-class'></div>
<div id='logo'></div>
<button id='switch'>switch</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
//put it in an IIFE so the variables are scoped down
(function(){
//constants, don't need to declare them in the click function over and over
var classes = ["vert", "escalier","reverse","demi_escalier"
,"demi_escalier_2","ligne" ];
//keep track of the last class used, -1 initial so no chance of mismatch
var lastNumber = -1;
var $logo = $("#logo");
$("#switch").on('click', function() {
//get a new index
var nextClass = Date.now() * 100 % classes.length;;
//while they match, keep getting a new one
while (nextClass === lastNumber) {
nextClass = Date.now() * 100 % classes.length;
}
$logo.removeClass().addClass(classes[nextClass]);
//save it off so we can do the double check again on the next execution
lastNumber = nextClass;
});
})();
Im still new at javascript ive been learning the concepts for several months and this is my first time taking a crack at it.
Im trying to create a carousel using css3 and Javascript (no Jquery)
the console keeps throwing an error.
Uncaught TypeError: Cannot read property display of undefined
The following is my html and javascript code
var slideShow = document.querySelectorAll('.inside');
for (var i = 0; i < slideShow.length; i++) {
setTimeout(function() {
slideShow[i].display.style = 'inline-block';
}, 2000)
}
<div class="inside">
<div class="inner1">
<h1>This is Inner div 1</h1>
</div>
<div class="inner2">
<h1>This is Inner div2</h1>
</div>
<div class="inner3">
<h1>This is Inner div3</h1>
</div>
<div class="inner4">
<h1>This is Inner div4</h1>
</div>
</div>
Aside from display and style being in the wrong order, the problem is that by the time the setTimeout callback function is executed, the for loop has already ended, and i is equal to the length of the nodeList (and since the last element's index is one less than the length of the nodeList, an error is thrown).
You could capture the value of i in an IIFE:
Example Here
var slideShow = document.querySelectorAll('.inside');
for (var i = 0; i < slideShow.length; i++) {
(function (i) {
setTimeout(function () {
slideShow[i].style.display = 'inline-block';
}, 2000 * (i + 1));
})(i);
}
or you could use the .forEach() method:
Example Here
var slideShow = document.querySelectorAll('.inside');
Array.prototype.forEach.call(slideShow, function (el, i) {
setTimeout(function () {
el.style.display = 'inline-block';
}, 2000 * (i + 1));
});
Alternatively, you could just use setInterval:
Example Here
var slideShow = document.querySelectorAll('.inside');
var i = 0;
var interval = setInterval(function () {
if (i < slideShow.length) {
slideShow[i].style.display = 'inline-block';
i++;
} else {
clearInterval(interval);
}
}, 2000);
You have display and style in the wrong order.
It should be slideShow[i].style.display='inline-block';
Additionally, slideShow is only an array-like object of length 1: it contains the div .inner but not its children. If you want to iterate through the child elements, use
var slideShow = document.querySelector('.inside').children;
Edit: As Josh pointed out in a separate answer, you have another problem as well in using setTimeout within a for loop. By the time the function inside the timeout executes, i will be 4, which will give you an undefined value.
If you insist on using a for loop, you can also do this using the forEach method. However, slideShow is not technically an array, but rather an "array-like object", so it does not have its own forEach method. Instead, you must invoke the Array.prototype method as such:
[].forEach.call(slideShow, function(item) {
setTimeout(function() {
item.style.display = 'inline-block';
}, 2000);
});
problem is you are only selecting div.inside and it is not returning div.inner
Try this if you want to select all .inner
change class="inside" to id="inside" and copy this js
var slideShow=document.getElementById("inside").querySelectorAll('div');
slideShow[1].style.backgroundColor = "red";
for (var i=0; i<slideShow.length; i++){
setTimeout(myFun(i), 2000)
}
function myFun(i ){slideShow[i].style.display = "inline-block";}
I'm currently working on a site that is using ajax to pull content in when an anchor link is clicked. I'm hoping to create a custom next/prev button using an array of predefined page links.
I'm trying to use a array as a counter to move through the pages when the next button is clicked. But I would like to use the current href attribute as a starting point then would move through the array by plus or minus one depend which button is click.
Here's the current codepen I'm working on http://codepen.io/veryrobert/pen/ocIhl
HTML:
<a id="value1" href="one.html">NEXT</a>
<a id="value2" href="">PREV</a>
Jquery:
$(function(){
var pages = [ "one.html", "two.html", "three.html", "four.html" ];
var prev = "#value2";
var next = "#value1";
// This works as a starting point
counter = 0;
// But I'd really like this to be the starting point
// counter = $(next).attr("href");
$(next).click(function(e){
e.preventDefault();
counter = (counter + 1) % pages.length;
});
$(prev).click(function(e){
e.preventDefault();
counter = (counter - 1) % pages.length;
$(prev).attr( "href", counter );
});
});
I'm not really great a JavaScript so please forgive me if this is a stupid approach or I'm going about this completely the wrong way.
You can try this
function getCounter(element, array) {
var href = element.getAttribute('href');
for ( var i=0; i < array.length; i++) {
if ( array[i] === href ) {
return i;
}
}
return -1;
}
You use it like this:
counter = getCounter( document.getElementById(next), pages );
Note: If you intend to use jQuery I am not sure what it returns when you call $(next).attr('href').
element.getAttribute('href') would return 'one.html' but
element.href would return 'host.com/one.html'