DIV animation and property change - javascript

I'm trying to simulate TCP packet transmission and sliding window, and fortunately I've made much progress. But now I want to fix a minor issue with the sliding window, which is a sliding DIV:
Hopefully if you are familiar with TCP's slow start, the window size double up to a number, and then increments by one. This is working. Now what I want to fix is sliding to right. So I want to automatically slide one step right when each ack is received at the original machine. Currently it does not move when the ack is received; so each time I press the button, it retransmits many of the previous packets! My work is here: http://web.engr.illinois.edu/~shossen2/CS438/Project/
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
var ssth= $("#ssth").val();
var window_left=0;
for (var i = 1; i <= 32; i++) {
$('#table').append("<div class='inline' id='"+i+"'>"+i+"</div>");
}
document.getElementById(1).style.width = 22;
$("button").click(function() {
if (items < ssth) {
if (items == 0)
items = 1;
else
items = items * 2;
count++;
} else {
items = items + 1;
}
window_left += 20;
window_width=items * 20;
document.getElementById("window_size").innerHTML = items;
document.getElementById("window").style.left= window_left + "px";
document.getElementById("window").style.width=window_width + "px";
speed = +$("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + (parseInt(packetNumber) + parseInt(window_left/20) -1) + "</font>").appendTo(div);
packetNumber++;
div.css({
left: left
/* opacity: 0*/
}).fadeOut(0);
//div.hide();
//left += 20;
}
}
function animateDivs() {
$(".t").each(function (index) { // added the index parameter
var packet = $(this);
packet
.delay(index * 200)
.fadeIn(200, function() {
$('#table #' + (index + window_left/20)).css({background:'yellow'});
})
.animate({left: '+=230px'}, speed)
.animate({left: '+=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '+=20px',
backgroundColor: "#f09090"
})
.text('a' + packet.text());
})
.delay(500)
.fadeIn(200)
.animate({left:'-=230px'}, speed)
.animate({left:'-=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '-=20px',
backgroundColor: "#90f090"
});
$('#table #' + (index + window_left/20)).css({background:'lightgreen'});
});
}).promise().done(function(){
$(".packets").empty();
});
}
});

Related

jQuery slider doesn't rotate

I have a slider rotator on my site but it doesn't rotate items automatically in the boxes - navigation works and rotate but I want it to rotate automatically, right after I enter the site.
This is my js:
$(document).ready(function() {
var nbr = 0;
$('.slider').each(function() {
var slider = $(this);
//get width and height of the wrapper and give it to the UL
var wrapperwidth = $(slider).width() * $(slider).find('ul > li').size();
$(slider).find('ul').css('width', wrapperwidth);
var wrapperheight = $(slider).height();
$(slider).find('ul').css('height', wrapperheight);
//set my li width
var width = $(slider).width();
$(slider).find('ul li').css('width', width);
//set my counter vars
var counter = $(slider).find('ul > li').size();
var decount = 1;
var autocount = 1;
if (counter > 1) {
//create my number navigation
var createNum = 1;
$(slider).after('<ul class="numbers"><li></li></ul>');
var numbers = $(slider).parent().find('.numbers');
$(numbers).find('li:first-child').html(createNum+'_'+nbr).addClass('activenum').attr('id', 'id1_'+nbr);
while ( createNum != counter) {
createNum++;
$(numbers).append("<li id='id"+createNum+"_"+nbr+"'>"+createNum+"_"+nbr+"</li>");
}
//get my number-width (number navigation should always be centered)
var numwidth = $(slider).find('.numbers li:first-child').width() * $(slider).find('.numbers li').size();
$(slider).find('.numbers').css('width', numwidth);
}
nbr++;
});
//make the number clickable
$(".numbers li").click(function() {
var slider = $(this).closest('.sliderWrapper');
var slider0 = $(slider).find('.slider');
var clickednum = $(this).html().split('_')[0] * - $(slider0).width() + $(slider0).width();
$(slider0).find('ul').animate({ left: clickednum }, 400, 'swing', function() { });
$(slider).find('.activenum').removeClass('activenum');
$(this).addClass('activenum');
decount = $(this).html();
});
rotateSwitch = function(sliderW, speed) {
var sliderWrap = sliderW;
play = setInterval(function() {
var nextNum = parseInt($($(sliderWrap).find(".numbers li.activenum")).html().split('_')[0])+1;
if (nextNum > $(sliderWrap).find(".numbers li").length) {
nextNum = 1;
}
//console.log("nextnum: "+nextNum+", numbers length: "+$(sliderWrap).find(".numbers li").length);
$(sliderWrap).find(".numbers li").each(function() {
if( parseInt($(this).html().split('_')[0]) == nextNum )
$(this).click();
});
}, speed);
};
makeAutoSlide = function(sliderWrap, speed) {
if ($(sliderWrap).length > 0 && $(sliderWrap).find(".numbers li").length > 1) {
rotateSwitch(sliderWrap, speed);
$(sliderWrap).find(".slider li").hover(function() {
if ($(sliderWrap).find(".numbers li").length > 1) {
clearInterval(play); //Stop the rotation
}
}, function() {
if ($(sliderWrap).find(".numbers li").length > 1) {
rotateSwitch(sliderWrap, speed); //Resume rotation timer
}
});
}
};
});
I'm not really sure if this is a problem with setInterval and clearInterval or I wrote something wrong.
I put code in jsFiddle, so you know how the structure looks like.
http://jsfiddle.net/gecbjerd/1/
I appreciate for help.
Cheers

Jquery Carousel - calculations if active slide is not one with specific ID then to slide to it.

The question isn't massively helpful I suppose so I'll try to be as clear as I can.
So I have a setup where my header has 4 anchor texts in them. The First part of the body has a custom jquery carousel in it.
What I'm trying to acheive is basically make it so that when any of the four anchor links in the header are clicked they scroll to a specific slide which I have given an ID. The issue I have of course is allowing for the carousel to have any slide active and having the anchor links calculate which slide is active and how much it needs to slide to get to the correct slide.
Here is the jquery for the carousel:
var carousel; // used as the object for the carousel
var carousels = []; // will hold any and all carousels on the page
var preventTimeouts = false;
var intervals = [];
$(document).ready(function () {
carousels.push(new carousel('slideshow_window', 'slidesHolder', '.slide', 920, 10000, 1000, true));
});
carousel = function CarouselSlider(windowName, slideCollectionWrapper,slideCollection, slideWidth, slideChangeInterval, slideChangeSpeed, requireNavButtons) {
// Variables
var slideWidth = slideWidth; // the width of each slide
var slides_array = $(slideCollection).toArray();
var numberOfSlides = slides_array.length;
var slideChangeInterval = slideChangeInterval; // how often the slides will automatically change
var slideChangeSpeed = slideChangeSpeed; // how fast the slides change
var slideIntervalId; // holds the interval event (the event for the next time that the slides should change)
var animating = false; // used to track whether an animation is underway
var currentPosition = 0; // used to highlight the centre image to begin with
var requireNavButtons = requireNavButtons;
var windowName = windowName;
var collectionWrapper = slideCollectionWrapper;
// Carousel
$('#' + windowName).append("<div id=\"" + collectionWrapper + "\"></div>"); // set up the collection wrapper
$('#' + collectionWrapper).css('width', slideWidth * numberOfSlides);
$('#' + collectionWrapper).css('position', "relative");
for (var i = 0; i < slides_array.length; i++) // add items from the collection to the wrapper
$('#' + collectionWrapper).append(slides_array[i]);
$('#' + collectionWrapper).css('left', 920 - slideWidth);
// for (i = 0; i < slides_array.length; i++) { // run one round of the carousel to ensure correct positioning
// currentposition++;
// moveslide(true, true); // set 'forced' to true to disable the animation
// }
function changePosition(forwards) {
forwards ? currentPosition++ : currentPosition--;
moveSlide(forwards, false);
}
function moveSlide(forwards, forced) {
var nextSlide;
animating = true;
if (forwards) {
nextSlide = currentPosition % numberOfSlides;
var t_dur = forced ? 0 : slideChangeSpeed;
$('#' + collectionWrapper).append(slides_array[nextSlide]);
$('#' + collectionWrapper).append(slides_array[nextSlide + 1 > numberOfSlides - 1 ? 0 : nextSlide + 1]); // load the next two slides
$('#' + collectionWrapper)
.animate({ left: "-=" + slideWidth, queue: false },
t_dur,
function () {
$('#' + collectionWrapper + ' ' + slideCollection + ':first').remove();
$('#' + collectionWrapper).css('left', 0);
animating = false;
});
}
else {
nextSlide = (currentPosition % numberOfSlides);
$('#' + collectionWrapper).prepend(slides_array[nextSlide - 1 < 0 ? numberOfSlides + nextSlide : nextSlide]);
$('#' + collectionWrapper).prepend(slides_array[nextSlide < 0 ? numberOfSlides + nextSlide : nextSlide]);
$('#' + collectionWrapper).css('left', 0 - slideWidth); // increase offset to account for prepended slides
$('#' + collectionWrapper)
.animate({ left: "+=" + slideWidth, queue: false },
slideChangeSpeed,
function () {
$('#' + collectionWrapper + ' ' + slideCollection + ':last').remove();
animating = false;
});
}
}
/*
Navigation buttons
*/
$("#next").click(function () {
if (!animating) { // only queue one click at a time
changePosition(true);
}
});
$("#prev").click(function () {
if (!animating) {
changePosition(false);
}
});
$("#prevSearch").click(function () {
if (!animating) {
changePosition(false);
}
});
$("#prevSearch2").click(function () {
$("#modalContainer").hide();
if (!animating) {
changePosition(false);
}
});
}

jQuery animation works with only one element

I need to make it working for all my elements under Which nothing should fade (images).
Currently works only for the div.logo tag
I guess at the moment the reason mine <h1> element is now allowing animations underneath is that when I am getting the .top(), .left() and so on, you are doing it for the last element in the list.
I need to get the borders of each element in the resulting list.
Any help would be much appreciated
Demo: http://jsfiddle.net/z9b8S/
JS:
function displayThese(selectorString) {
var $heading = $(selectorString);
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
var h1left = $heading.position().left;
var h1right = h1top + $heading.width();
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
var left = $e.position().left;
var right = left + $e.width();
return top > h1bottom || bottom < h1top || left > h1right || right < h1left;
});
return divs;
}
(function fadeInDiv() {
var divsToChange = displayThese('h1, div.logo');
var elem = divsToChange.eq(Math.floor(Math.random() * divsToChange.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
$(window).resize(function () {
// Get items that do not change
var divs = $('li').not(displayThese());
divs.css({
opacity: 0.3
});
});

shuffling position of three images in html/javascript

I am trying to achieve shuffle three images in a random order
This is what i have achieved so far
shuffle jsfiddle
I wanted to shuffle them with each other randomly
$(document).ready(function () {
shuffle(1);
});
var shipsArray = new Array();
shipsArray = ["1", "2", "3"];
function shuffle(level) {
for (i = 0; i < 30; i++) {
var j = i % 3;
var favorite = shipsArray[Math.floor(Math.random() * shipsArray.length)];
if (j != favorite) {
var newposition = $("#ship" + shipsArray[favorite]).position();
var tempPosition = $("#ship" + shipsArray[j]).position();
$("#ship" + shipsArray[j]).animate({ "left": newposition.left, "top": newposition.top });
$("#ship" + shipsArray[favorite]).animate({ "left": tempPosition.left, "top": tempPosition.top });
}
}
}
Here is my final solution (sort of).
I had to resort to using setTimeout() to do the timing right.
JSFiddle
HTML (unchanged, just for completeness)
<div id="MainDiv">
<img id="ship1" src="http://cdn-img.easyicon.net/png/154/15462.png" />
<img id="ship2" src="http://cdn-img.easyicon.net/png/154/15462.png" />
<img id="ship3" src="http://cdn-img.easyicon.net/png/154/15462.png" />
</div>
CSS (also unchanged)
#MainDiv {position:absolute;}
#MainDiv img {position:absolute;}
#ship1 {top:10px; left:200px;}
#ship2 {top:210px; left:0px;}
#ship3 {top:210px; left:400px;}
JS
var ships = [] /* array of ships */
var time_anim = 500 /* anim time */
$(document).ready(function () {
ships = $("#MainDiv img"); /* find ships */
shuffle(6); /* wheeee */
});
function shuffle(level) {
/* do the animation */
var c = randInt(2, 3)
cycle(getElements(ships, c))
if (level > 1) {
setTimeout(function () {
shuffle(level - 1)
}, time_anim)
}
}
function randInt(min, max) {
/* get random integer */
return Math.floor(Math.random() * (max - min + 1) + min);
}
function cycle(items) {
/* cycle ships in array */
var pos0 = $(items[0]).position()
for (i = 1; i < items.length; i++) {
var sh = items[i];
var shp = $(sh).position();
$(items[i - 1]).animate({
"left": shp.left,
"top": shp.top
}, time_anim);
}
$(sh).animate({
"left": pos0.left,
"top": pos0.top
}, time_anim);
}
function getElements(arr, n) {
/* Get n random elements from array */
var used = []
var result = []
while (result.length < n && result.length < arr.length) {
var i = randInt(0, arr.length - 1)
if (jQuery.inArray(i, used) !== -1) {
continue;
}
used.push(i)
result.push(arr[i])
}
return result;
}
(Maybe it can be done a bit easier, but w/e - it works.

jQuery How to Have Variable Increment by Value in a Recursive Function

I have a JS Function which is called in document.ready. The intent is as it scrolls to the bottom window, it'll load more from the JSON API.
The API has the parameter offset and limit. Offset controls which subset of results you are seeing. For ex. 20-40 would be offset=20 and limit controls how many you can view at once.
I thought I would approach this with a recursive function which calls itself each time the user goes to the bottom of the window, with window.scroll. Once they go to the bottom, it'll increment the offset by 20 each time, then run the function again.
Problem: I can't seem to get it to increment the variable by 20 to make this work. Thoughts?
function getData(offset) {
var jsonCallback = "&jsoncallback=?";
//var offset = 20;
//var offset += 20;
var limit = 20;
var characterURL = "http://api.example.com/character&byId=" + characterID + "&offset=" + offset + "&limit=" + limit;
$.getJSON(characterURL + jsonCallback, function(data) {
for (i=0; i < (data.data.results).length; i++) {
var $characterUl = $("<ul>");
$characterUl.appendTo("#characterComics");
$("<li>").text(data.data.results[i].title).appendTo($characterUl);
$("<li>").text(data.data.results[i].id).appendTo($characterUl);
$("<li>").text(data.data.results[i].release_date).appendTo($characterUl);
if (data.data.results[i].release_date > 0) {
$characterLi.text(data.data.results[i].issue_number).appendTo($characterUl);
}
}
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 10) {
while ((data.data.results).length === offset || (data.data.results).length > offset) {
offset = offset+20;
$("<div>").text(offset).appendTo("body");
getComics(offset);
}
}
});
});
}
$(document).ready(function() {
var $characterComics = $("<div>", {id : "characterComics"});
$characterComics.appendTo("body");
getData(0);
});
UPDATED
Read this more as a pseudo-code
function getData(offset) {
var jsonCallback = "&jsoncallback=?",
characterURL = "http://api.example.com/character&byId=" + characterID + "&offset=" + offset + "&limit=" + limit;
$.getJSON(characterURL + jsonCallback, function(data) {
for (i=0; i < (data.data.results).length; i++) {
var $listItem = $("<li>");
listItem.append("<span>"+data.data.results[i].title+"</span>");
listItem.append("<span>"+data.data.results[i].id+"</span>");
listItem.append("<span>"+data.data.results[i].release_date+"</span>");
if (data.data.results[i].release_date > 0) {
listItem.append("<span>"+data.data.results[i].issue_number+"</span>");
}
listItem.appendTo($characterUl);
itemsLoaded++;
}
});
}
$(document).ready(function() {
var $characterComics = $("<div>", {id : "characterComics"}),
$characterUl = $("<ul>"),
offset = 0,
itemsLoaded = 0;
limit = 20;
$characterComics.appendTo("body");
$characterUl.appendTo($characterComics);
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 10) {
if ("check here if you reached your offsets") {
offset = offset+20;
getData(offset);
}
}
});
// get your first set of data
getData(0);
});

Categories