I'm relatively new to JavaScript & jQuery. I'm trying out some code for an image slider which works fine on an image click event. However, I want it to run all by itself after the document loads. How can I achieve this? I tried to place the code inside $(document).ready() but it doesn't work that way. Here's my code:
<script>
var total = 4;
var present = 1;
var next = 2;
$(document).ready(function () {
$("#right").click(function () {
present_slide = "#slide" + present;
next_slide = "#slide" + next;
$(present_slide).css("top", "200px");
$(next_slide).css("top", "0px");
present++;
next++;
if (present == (total + 1)) {
present = 1;
next = 2;
for (i = 1; i <= 4; i++) {
$("#slide" + i).css("top", "200px");
}
$("#slide1").css("top", "0px");
}
});
});
</script>
Here - #right is the id associated with an img element. #slide1, #slide2, etc are the ids associated with the divs that hold multiple images.
$(document).ready(function (){
$( "#right" ).trigger( "click" );
});
try to replace $(document).ready() by $(window).onload = function(){ ... }
Either remove the $("#right").click(function () { or add $('#right').trigger('click').
var total = 4;
var present = 1;
var next = 2;
$(document).ready(function () {
present_slide = "#slide" + present;
next_slide = "#slide" + next;
$(present_slide).css("top", "200px");
$(next_slide).css("top", "0px");
present++;
next++;
if (present == (total + 1)) {
present = 1;
next = 2;
for (i = 1; i <= 4; i++) {
$("#slide" + i).css("top", "200px");
}
$("#slide1").css("top", "0px");
}
});
Or
var total = 4;
var present = 1;
var next = 2;
$(document).ready(function () {
$("#right").click(function () {
present_slide = "#slide" + present;
next_slide = "#slide" + next;
$(present_slide).css("top", "200px");
$(next_slide).css("top", "0px");
present++;
next++;
if (present == (total + 1)) {
present = 1;
next = 2;
for (i = 1; i <= 4; i++) {
$("#slide" + i).css("top", "200px");
}
$("#slide1").css("top", "0px");
}
}).trigger('click');
});
You can manually trigger the `click' event for the image when the window loads by
$(window).load(function() {
$("#right").trigger('click');
}
This would trigger the click once all the resources are loaded.
At the bottom of your script block, place this line:
$("#right").trigger('click');
Related
I have function that works after window.onload, but how to run it just after scrolled to the needed . I understand that using jQuery is easier, but I need to do in native JS.
window.onload = function move() {
var width = 1;
var elem = document.getElementsByClassName("myBar");
var maxValue = document.getElementsByClassName('max-value');
for(var i = 0; i < elem.length; i++) {
var params = {
elem: elem[i],
maxElem: maxValue[i],
width: width,
interval: null
};
params.interval = setInterval(frame, 20, params);
}
function frame(aParams) {
if (aParams.width >= aParams.maxElem.dataset.max) {
clearInterval(aParams.interval);
} else {
aParams.width++;
aParams.elem.style.backgroundColor = 'blue';
aParams.elem.style.width = aParams.width + '%';
aParams.maxElem.innerHTML = aParams.width + '%';
}
};
};
https://codepen.io/Slava91/pen/PjpGGr
Try this, it will trigger the animation again when you will scroll near to the ul element. #percentage is the id I have given to the ul element in your html.
window.onload = move();
function move() {
var width = 1;
var elem = document.getElementsByClassName("myBar");
var maxValue = document.getElementsByClassName('max-value');
for(var i = 0; i < elem.length; i++) {
var params = {
elem: elem[i],
maxElem: maxValue[i],
width: width,
interval: null
};
params.interval = setInterval(frame, 20, params);
}
function frame(aParams) {
if (aParams.width >= aParams.maxElem.dataset.max) {
clearInterval(aParams.interval);
} else {
aParams.width++;
aParams.elem.style.backgroundColor = 'blue';
aParams.elem.style.width = aParams.width + '%';
aParams.maxElem.innerHTML = aParams.width + '%';
}
};
}
isScrolled = false;
window.onscroll = function loadItBack(){
var rec = document.getElementById("percentage").getBoundingClientRect();
if(window.scrollY > 600 && !isScrolled){
isScrolled = true;
move();
}else if(window.scrollY < 600){
isScrolled = false;
}
};
For your every li, you can use getBoundingClientRect to execute your animation.
Don't forget to set a flag once animation completed, else, it will execute on every scroll.
Her is my new code with setinternal of 4 images. However, I am trying to have an infinite loops of the same images. Can you help me to understands how to create a setInterval loop.
<script type="text/javascript" >
var OpenWindow = window.open("","","top=100, left=400,resizable=yes,height=550,width=550,menubar=yes,location=yes,resizable=yes,scrollbars=yes");
var imgURLS = ['Oculus.jpg', 'future-vr.jpg', 'morpheus.jpg', 'samsungvr.jpg'];
var imgIndex = 0;
var timer = setInterval(function() {
for (var imgIndex = 0; j < imgURLS.length; j++)
{
for (var imgIndex = 0; i < imgURLS.length; i++)
{
clearInterval(timer);
} else {
OpenWindow.document.write("<div class='css-slideshow'>");
OpenWindow.document.write("<figure>");
OpenWindow.document.write('<img src ="' + imgURLS[imgIndex++] + '">');
OpenWindow.document.write("</figure>");
OpenWindow.document.write("</div>");
}
}, 3000);
</script>
I just figure out how to make longer loops. However, my images are showing broke?
<script type="text/javascript" >
var OpenWindow = window.open("","","top=100, left=400,resizable=yes,height=550,width=550,menubar=yes,location=yes,resizable=yes,scrollbars=yes");
var imgURLS = ['Oculus.jpg', 'future-vr.jpg', 'morpheus.jpg', 'samsungvr.jpg'];
var imgIndex = 0;
var i = setInterval(function() {
imgIndex++;
if(imgIndex === 20) {
clearInterval(i);
} else {
OpenWindow.document.write("<div class='images-1'>");
OpenWindow.document.write('<img src ="' + imgURLS.length + '">');
OpenWindow.document.write("</div>");
}
}, 3000);
</script>
I figure out why the image were broke. it was missing this imgURLS[imgIndex]
new code is:
OpenWindow.document.write('<img src ="' + imgURLS[imgIndex] + '">');
OpenWindow.document.write('<img src ="' + imgURLS.length + '">');
Here's a simple way with setTimeout.
1) Add an id to your containing div and target it.
var image = document.querySelector('#css-slideshow img');
2) Use setTimeout to repeatedly call the same loop function with increments of count. If count equals the length of the images array, set it to zero.
function carousel() {
var timer, count = 0;
var loop = function loop(count) {
if (count === imgURLS.length) count = 0;
image.src = imgURLS[count];
timer = setTimeout(loop, 2000, ++count);
}
loop(count);
}
carousel();
DEMO
I have different boxes with different id
<div id="49" align="center" class="feed_box_id"></div>
<div id="50" align="center" class="feed_box_id"></div>
<div id="51" align="center" class="feed_box_id"></div>
i want to scroll a next id whenever the same button is clicked.
I tried
scrollTop
scrollTo
window.location.href
But couldn't find a way out.
if you want, here is my fuzzy code
var id_down = parseInt($(".feed_box_id").attr("id")) - 1;
$("#feed_down").click(function() {
window.location.href = "#" + id_down;
});
var id_up = parseInt($(".feed_box_id").attr("id")) + 1;
$("#feed_up").click(function() {
window.location.href = "#" + id_up;
});
Maintain a variable that keeps the track of the last clicked id.
var lastclicked={id:49};
$("#feed_up").click(lastclicked, function(e) {
if($("#" + (e.data.id+1)).length>0)
{
window.location.href = "#" + (e.data.id+1);
e.data.id++;
}
});
$("#feed_down").click(lastclicked, function(e) {
if($("#" + (e.data.id-1)).length>0)
{
window.location.href = "#" + (e.data.id-1);
e.data.id--;
}
});
Okay, you can create the fiddle by yourself.
HTML:
<button id="feed_down">feed_down</button>
<button id="feed_up">feed_up</button>
JS:
for(var i=0;i<100;i++)
{
$('<div id="' + (i) + '" align="center" class="feed_box_id">'+ (i) +'</div>').appendTo($('body'));
}
var lastclicked={id:49};
$("#feed_up").click(lastclicked, function(e) {
if($("#" + (e.data.id+1)).length>0)
{
window.location.href = "#" + (e.data.id+1);
e.data.id++;
}
});
$("#feed_down").click(lastclicked, function(e) {
if($("#" + (e.data.id-1)).length>0)
{
window.location.href = "#" + (e.data.id-1);
e.data.id--;
}
});
CSS:
#feed_down
{
position:fixed;
top:0;
right:0
}
#feed_up
{
position:fixed;
top:0;
right:100px
}
There are 2 ways: using only class without ids, using ids and no class is needed.
Class only:
var elementIndex = 0, elements = document.getElementsByClassName('myClass');
var scrollToElement = function(element){
window.scrollTo(0, element.getBoundingClientRect().top);
};
var nextElement = function(){
if(++elementIndex >= elements.length)
elementIndex = 0;
scrollToElement(elements[elementIndex]);
};
var previousElement = function(){
if(--elementIndex < 0)
elementIndex = elements.length - 1;
scrollToElement(elements[elementIndex]);
};
Id only (may be not only numbers):
var elementIndex = 0, elements = ['id1', 'myDog', 'last'];
var scrollToElement = function(element){
window.scrollTo(0, element.getBoundingClientRect().top);
};
var nextElement = function(){
if(++elementIndex >= elements.length)
elementIndex = 0;
scrollToElement(document.getElementById(elements[elementIndex]));
};
var previousElement = function(){
if(--elementIndex < 0)
elementIndex = elements.length - 1;
scrollToElement(document.getElementById(elements[elementIndex]));
};
I tried to count an element clicks, and, in the right number call some action.
var count = 0;
document.getElementById("rolarbaixo").onClick = function(e) {
if( count >= 3 ) {
var elem = document.getElementById("noticia");
elem.setAttribute("style","top: 0px;");
}
else {
count ++;
}
};
When i clicked 3 times in the link "rolarbaixo" the div "noticia" set the "top: 0px;", but this doesn't work.
Why?
count ++ should be count++. If you press F12, you will be able to get to the developer tools and debug the javascript.
It's onclick in lowercase
var count = 0;
document.getElementById("rolarbaixo").onclick = function (e) {
if (count >= 2) {
var elem = document.getElementById("noticia");
elem.style.top = "0px";
} else {
count++;
}
};
FIDDLE
And it's >= 2 for three clicks (zero based and all).
AS the question is tagged jQuery, this would be it
$('#rolarbaixo').on('click', function() {
var clicked = $(this).data('clicked') || 0;
if (clicked >= 2) $('#noticia').css('top', 0);
$(this).data('clicked', ++clicked);
});
FIDDLE
Misprint in else statement and change onclick to lowercase:
var count = 0;
document.getElementById("rolarbaixo").onclick = function(e) {
if( count >= 3 ) {
var elem = document.getElementById("noticia");
elem.setAttribute("style","top: 0px;");
} else {
count++;
}
};
I am not that strong when it comes to JS. However I have written a little bit of code that does exactly what I want it to do.
function showDiv(divName)
{
var divnameids = new Array();
divnameids[0] = "accessories";
divnameids[1] = "connections";
divnameids[2] = "features";
divnameids[3] = "phones";
divnameids[4] = "services";
for (var i=0;i<divnameids.length;i++)
{
if (divnameids[i] == divName) divnameids.splice(i, 1);
}
for (var i=0;i<divnameids.length;i++)
{
document.getElementById(divnameids[i]).style.display='none';
document.getElementById('but' + divnameids[i]).className = "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only";
}
document.getElementById('but' + divName).className = "quotebutton ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only";
document.getElementById(divName).style.display='block';
}
This works but the corresponding buttons triggering the opening and closing of divs like tabs.
However I now wish to use another button to skip through these divs in order (the same order as the JS array)
could somebody suggest the best approach to doing this?
This code should open each div, and then close the previous one:
var currentPos = 0;
$('#yourButtonId').on('click', function () {
if (currentPos > 0)
$('#' + divnameids[currentPos - 1]).hide();
if (currentPos == 0) // hide the last tab when coming back to the start
$('#' + divnameids[divnameids.length - 1]).hide();
$('#' + divnameids[currentPos]).show();
currentPos += 1;
// Reset the current position to 0
if (currentPos >= divnameids.length)
currentPos = 0;
});
Assuming that you wanted a pure Javascript solution, this works (assuming that I was in the ballpark on your HTML):
function nextDiv() {
var divnameids = new Array();
divnameids[0] = document.getElementById("accessories");
divnameids[1] = document.getElementById("connections");
divnameids[2] = document.getElementById("features");
divnameids[3] = document.getElementById("phones");
divnameids[4] = document.getElementById("services");
var len = divnameids.length;
for(var i=0; i < len; i++) {
if(i == (len - 1)) {
divnameids[len-1].style.display = 'none';
divnameids[0].style.display = '';
break;
}
else {
if(divnameids[i].style.display == '') {
divnameids[i].style.display = 'none';
divnameids[i+1].style.display = '';
break;
}
}
}
}
JSFiddle: http://jsfiddle.net/yjf8w/
$(document).ready(function(){
$(".content-box-front").click(function(){
$(".full-content-back").fadeIn("slow");
$(".full-content-front").fadeIn("slow");
$(".content-box-front").fadeOut("slow");
$(".content-box-back").fadeOut("slow");
});
});
$(document).ready(function(){
$(".full-content-front").click(function(){
$(".full-content-back").fadeOut("slow");
$(".full-content-front").fadeOut("slow");
$(".content-box-front").fadeIn("slow");
$(".content-box-back").fadeIn("slow");
});
});
this should help put the name of the divs in where full-content.... is