Append div with interval in Jquery - javascript

Hi I need help regarding appending div while using 2 types of speed interval via 2 loops
Here is my sample code
<script type="text/javascript">
$(document).ready(function() {
for (var i = 0; i <= 300; i++) {
$(".wrapper").append("<div class='item' id='" + i + "'>" + i + "</div>");
if (i==300)
{
//I need this for loop to slow down my
//interval so div will display slower compared to the first 300
for (var i = 300; i <= 500; i++) {
$(".wrapper").append("<div class='item' id='" + i + "'>" + i + "</div>");
};
}
};
});
var step = 0;
function hideItemFunc() {
var interval = setInterval(function() {
$("#" + step).animate({
opacity: 1
}, 50);
step += 1;
}, 50);
}
</script>

I've done it using two interval()... But one function.
And use some variables to control iterations and delays (or speed).
Look how it slows when it reaches 300.
$(document).ready(function(){
var intervalSpeed = 20 // in milliseconds
var ratio_1=1; // 1 is 100% of the above delay
var ratio_2=10;
var animateSpeed=300; // in milliseconds
var i=0;
function twoSpeedInterval(){
// Append.
$(".wrapper").prepend("<div class='item' id='" + i + "'>" + i + "</div>");
// Animate.
$("#" + i).animate({opacity: 1},animateSpeed);
// Condition to slow or stop.
if (i==300){
clearInterval(interval_1); // Stop the 1st interval.
// Start 2nd interval.
interval_2 = setInterval(twoSpeedInterval,intervalSpeed*ratio_2);
animateSpeed = animateSpeed*ratio_2;
}
if (i==500){
clearInterval(interval_2); // Stop the 2nd interval.
}
i++;
}
// Start 1st interval.
var interval_1 = setInterval(twoSpeedInterval,intervalSpeed*ratio_1);
var interval_2;
});
.item{
opacity:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper"></div>

Just having a bit fun with it, I used jQuery .queue() for this and made i a global variable.
var i = 0;
$(document).ready(function() {
for (i = 0; i <= 300; i++) {
$(".wrapper").append("<div class='item' id='" + i + "'>" + i + "</div>");
}
for (j = 300; j <= 500; j++) {
$(".wrapper").delay(1000).queue(function(next) {
$(this).append("<div class='item' id='" + i + "'>" + i + "</div>");
i++;
next();
});
}
});
var step = 0;
function hideItemFunc() {
var interval = setInterval(function() {
$("#" + step).animate({
opacity: 1
}, 50);
step += 1;
}, 50);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wrapper"></div>

As commented before,
You will have to use recursion with timer to add delay in loops.
You can check this JSFiddle as a sample or use following snippet to debug:
Note: Please note the difference in the delay for every value where count%3 === 0.
var count = 0;
function animate(delay) {
setTimeout(function() {
var div = $('<div class="tile" style="display: none">'+count+'</div>');
$('.content').append(div)
div.fadeIn()
if (++count < 10) {
animate(count % 3 === 0 ? 3000 : 1000)
}
}, delay || 1000)
}
animate();
.tile {
height: 40px;
margin: 5px;
border: 2px solid #ddd;
border-radius: 4px;
background: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="content"></div>

Related

how to create slideshow for string 64 type image in MVC

I'm having trouble to create image slideshow. An image fetched from data base and binded into view model. it working fine. now i want to create slideshow with available images. i had tried like this.
$(function () {
function loop() {
$('.slider .inner-wrap').fadeIn("slow").css('marginLeft', 0).delay(2000)
.animate({ "marginLeft": "-200px" }, 700).delay(2000)
.animate({ "marginLeft": "-400px" }, 700).delay(2000)
.fadeOut("slow", loop);
}
loop();
});
.slider {
width: 200px;
height: 200px;
overflow: hidden;
margin: 30px auto;
background-image: url('http://www.thatssotrue.com/images/ajax_loader.gif');
background-size: 50px 50px;
background-position: center center;
background-repeat: no-repeat;
}
.slider img {
width: 200px;
height: 200px;
}
.inner-wrap {
width: 600px;
}
.item-1, .item-2, .item-3 {
display: inline-block;
vertical-align: top;
}
<tr>
<td>
<div class="slider">
<div class="inner-wrap">
<img class=" item-1" id="slides" />
</div>
</div>
</td>
</tr>
this is how i had bind my images
for (var i = 0; i < images.length; i++) {
var imgid = i;
var imagetemp = "<img id='" + imgid + "'style='margin:5px;cursor:zoom-in;width:200px;height: 150px;' onclick='getid(this)' src='" + clubimage[i] + "'>";// onclick='getid(this)'
var slider = "<img id='" + imgid + "'src='" + clubimage[i] + "'>";
$("#image").append(imagetemp);
$("#slides").append(slider);
}
My images unable to shows here. please help me. thankyou
Finally i had achieved my slideshow in knockout js. complete solutions is here.
my ajax response. I had call swapImage() method in it.
success: function (data) {
image = JSON.parse(data.imageResult);
self.bindimage(image);
for (var i = 0; i < image.length; i++) {
var imgid = i;
var imagetemp = "<img id='" + imgid + "'style='margin:5px;cursor:zoom-in;width:200px;height: 150px;' onclick='getid(this)' src='" + image[i] + "'>";
var imgslide = "<li><img class='slides' style='margin:5px' src='" +image[i] + "'/></li>";
$("#image").append(imagetemp);
}
swapImage();
if (data.imageResult == '"Invalid Connection"') {
alert("Invalid Connection");
}
i had created javascript method like this.
var i = 0;
function swapImage() {
var im = image[i];
$("#imgslide").empty();
var imgid = 'galimg' + i;
var imagesilde = "<img id='" + imgid + "'style=width:500px;height:450px;'rel='alternate' src='" + image[i] + "'/>";
$("#imgslide").fadeIn("slow", "swing");
$("#imgslide").append(imagesilde);
if (i < image.length - 1) i++; else i = 0;
setTimeout('swapImage()', 3000);
}
And bind into HTML tag like this.using selector
<div id="imgslide" />
Finally i got my requirement.

How do I loop a variable in the Javascript function call?

I have the following loop for a series of similar click events in jQuery. Everything works fine except for the last line below with the comment. How can I make each loop iteration call these functions respectively: step1(), step2(), step3(), etc.?
for (i = 0; i < 7; i++) {
$("#stepbox" + i).click(function(){
$("#step" + i).show();
$("#stepswrapper section").not("#step" + i).hide();
$("#stepbox" + i).addClass("stepboxactive");
$("#stepboxmain div").not("#stepbox" + i).removeClass("stepboxactive");
step + i(); // I'm stuck here. This doesn't work to create the function calls step1(), step2(), etc.
});
}
Assuming your functions are defined in the global context:
for (i = 0; i < 7; i++) {
$("#stepbox" + i).click(function(){
$("#step" + i).show();
$("#stepswrapper section").not("#step" + i).hide();
$("#stepbox" + i).addClass("stepboxactive");
$("#stepboxmain div").not("#stepbox" + i).removeClass("stepboxactive");
window["step" + i]();
});
}
make an array of the step functions.
var step = [
function () { /* step 0 */ },
function () { /* step 1 */ },
function () { /* step 2 */ }
// ...
];
for (i = 0; i < 7; i++) {
$("#stepbox" + i).click(function(){
$("#step" + i).show();
$("#stepswrapper section").not("#step" + i).hide();
$("#stepbox" + i).addClass("stepboxactive");
$("#stepboxmain div").not("#stepbox" + i).removeClass("stepboxactive");
step[i]();
});
}

How can I prevent my javascript from polling websites too fast?

I made this website quite a while ago for the purpose of grabbing random puu.sh images and displaying them. Also a warning, the content this site shows is user generated, and I can not guarantee it is SFW.
https://dl.dropboxusercontent.com/s/dlb1uke5udz8kwy/index.html
I just started looking at it again, and it appears it has some serious bugs with the systems it uses to gather content. How can I change my javascript so that it doesn't spam out puu.sh, and make it refuse connections?
Here is the code:
var currentThumb = 0;
function getImgUrl()
{
var text = (Math.round(Math.random() * 9)).toString();
//var text = '3T';
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < 4; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return 'http://puu.sh/' + text;
}
function open_in_new_tab(url)
{
var win=window.open(url, '_blank');
win.focus();
}
function getImages()
{
//var width = window.innerWidth;
var images = 10;
for(var i = 0;i < images;i++)
{
var url = getImgUrl();
document.getElementById('thumbs').innerHTML += '<img class="thumb" id="thumb' + i + '" src=' + url + '>';
if(i == 0)
{
document.getElementById('fullimage').innerHTML = '<img id="big" src=' + url + '>';
$('#thumb' + currentThumb).css('border','2px solid white');
}
}
}
function refreshImages()
{
var images = 10;
for(var i = 0;i < images;i++)
{
var url = getImgUrl();
$('#thumb' + i).attr('src',url);
}
$('img').css('border','');
$('#thumb' + currentThumb).css('border','2px solid white');
}
function resize()
{
var width = $(window).width();
var height = $(window).height();
$('#fullimage img').css('max-width',width);
$('#fullimage img').css('max-height',height - 87);
}
function setBig()
{
$('#big').attr('src',($('#thumb' + currentThumb).attr('src')));
$('img').css('border','');
$('#thumb' + currentThumb).css('border','2px solid white');
resize();
}
getImages();
$('img').error(function() {
$(this).attr('src',getImgUrl());
setBig();
});
$('#thumbs img').click(function() {
$('#fullimage').html('<img id="big" src=' + $(this).attr('src') + '>');
currentThumb = parseInt($(this).attr("id").match(/\d+/));
$('img').css('border','');
$(this).css('border','2px solid white');
resize();
});
$('#fullimage').click(function() {
open_in_new_tab($('#fullimage img').attr('src'));
});
$(window).resize(function() {
resize();
});
$(document).ready(function() {
resize();
});
The problem most likely lies in
$('img').error(function() {
$(this).attr('src',getImgUrl());
setBig();
});
Your main problem seems to be that you are spamming the servers when you hit a 404 because of the error handler. Try something like
$('img').error(function() {
var _this = this;
setTimeout(function () {
$(_this).attr('src',getImgUrl());
setBig();
}, 500); // Whatever timeout is good not to spam
});
Untested, but try this new getImages() function (replace the old one)
function getImages(images)
{
if (!images) {
document.getElementById('fullimage').innerHTML = '<img id="big" src=' + url + '>';
$('#thumb' + currentThumb).css('border','2px solid white');
images = 1;
}
document.getElementById('thumbs').innerHTML += '<img class="thumb" id="thumb' + i + '" src=' + url + '>';
images++;
if (images < 10) {
setTimeout(function() { getImages(images); }, 25);
}
}
It will be called 9 times, but the first time it should do what you were doing at i = 0 and 1; It will be fired every 25ms regardless of whether images have loaded yet or not. Increase that number (25) to slow it down.

function(){If fadeout, then append} is not working

I am aware of jQuery UI's sortable option, but drag-and-drop isn't what I'm looking for.
Due to the way of how accordions are laid out, I think in order to sort them, the best way to go about it is to change the id, unsafe as that sounds.
This is what one of my accordions look like.
Copy code
<table style="background: none repeat scroll 0% 0% rgb(186, 218, 85); display: none;" tabindex="-1" aria-selected="false" aria-controls="ui-accordion-accordion1-panel-2" id="ui-accordion-accordion1-header-2" role="tab" class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-accordion-icons"><span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-e"></span>
<tbody>
<tr>
<td>... Yadayada, content. End table tags.
This is the code I use.
function pagination() {
for (var i = 0; i < 10 ; ++i) {
var k = i * 1000;
var j = i * 100;
var index;
console.log("aftervar " + i);
if ($("#ui-accordion-accordion1-header-" + i).css("display") == "none") {
$("#ui-accordion-accordion1-header-" + i).attr("id", "ui-accordion-accordion1-header-" + j);
$("#ui-accordion-accordion1-panel-" + i).attr("id", "ui-accordion-accordion1-panel-" + j);
index = $("#ui-accordion-accordion1-header-" + j);
$("#accordion1").append($("#ui-accordion-accordion1-header-" + j));
console.log("if " + i);
} else {/*
k += 1;
$("#ui-accordion-accordion1-header-" + i).attr("id", "#ui-accordion-accordion1-header-" + k);
$("#ui-accordion-accordion1-panel-" + i).attr("id", "#ui-accordion-accordion1-panel-" + k);*/
}
}
$("#tabs-1 table:nth-of-type(odd)").css("background", "#BADA55");
$("#tabs-1 table:nth-of-type(even)").css("background", "#FFFFFF");
$("#table-headings").css("background", "#FFFFFF");
}
I'm using the ids to sort it out. The other problem is that the appends aren't working as they should (in fact, I put a console.log in there and it seems the if statement does not run sometimes). The elements stay where they are and the appended is typically text of the id or nothing at all.
http://jsfiddle.net/Cb3U2/5/
Someone else helped me on this issue. He warned me against using id's, but showed me how unreliable it is to see fadeout and fadein. I only know of separating the two through buttons.
http://jsfiddle.net/Cb3U2/7/
$("#ab-4").fadeOut();
$("#ab-7").fadeOut();
function foo() {
for (var i = 0; i < 10; ++i) {
var k;
var j = 10 + i;
if ($("#ab-" + i).css("display") == "none") {
$("#ab-" + i).html(i + " (different)");
$("#ab-" + i).attr("id","ab-" + j);
$(".wrapper").append($("#ab-" + j));
} else {
$("#ab-" + i).html(i + " (Same)");
}
$("table:nth-of-type(odd)").css("background", "orange");
$("table:nth-of-type(even)").css("background", "white");
}
}
//setTimeout(foo, 10000);
function seeme() {
$("#ab-4").fadeIn();
//$("#ab-7").fadeIn();
//$("#ab-14").fadeIn();
$("#ab-17").fadeIn();
};

retrieving array value on mouseover with javascript

I'm trying to figure out a way to retrieve and display the value of a div tag that is created with a 2D array using JavaScript. I figured either onclick or onmouseover would work but neither would in this approach. I would like to avoid creating 49 functions that does the same thing (just displaying the 'cell' the mouse is over).
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(cellId)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
// ???
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Thanks!
You can simply get the cell id by passing this.id into the function.
Try this:
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
console.log(cellId);
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Right now you have set up each cell element to call the function displayMe whenever the mouseover event occurs. When you call that function, you are passing the variable cellId as an argument. The problem is when that function is called, cellId is not defined. You can see this error pop up in your browser's developer console ("Uncaught ReferenceError: cellId is not defined").
You probably want to pass the cell element's id property, which you define dynamically here: id='area" + i + j + "'. You can use the id property of an element to look up the element (as you have done already), and get the text it contains via textContent.
To pass the cell element's id property, you need to use the this variable, like so: this.id. this will refer to the element that is triggering the event. So, if you change your onmouseover value of your div element to this: onmouseover='displayMe(this.id)', it will pass the appropriate value to your displayMe function, allowing you to do something like this:
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
With these adjustments, your code will look like this in its entirety:
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>

Categories