Change random result to sequence - javascript

How to change this random result into a sequence starting from lower number? I am new in JS and have tried to make modification with no solution. I hope anybody can help.
function randomFeed() {
var $el = $("#randomFeed");
var random = new Array('news1','news2','news3','news4','news5','news6');
var randomIndex = Math.floor(Math.random() * 4);
var newElement = random[randomIndex];
$el.prepend("<tr><td>" + newElement + "</td></tr>").find("tr").first().hide();
$el.find("tr").first().fadeIn();
if ($el.find("tbody tr").length > 20) {
$el.find("tbody tr").last().fadeOut(400, function() {
$(this).remove();
});
}
slimScrollUpdate($el.parents(".scrollable"));
setTimeout(function() {
randomFeed();
}, 3000);
}

So you need sequential news slide instead of random? Try this (note the global feedIndex variable)
var feedIndex = 0;
function randomFeed() {
var $el = $("#randomFeed"),
news = new Array('news1','news2','news3','news4','news5','news6'),
newElement = news[feedIndex++ % news.length];
//console.log(newElement);
$el.prepend("<tr><td>" + newElement + "</td></tr>").find("tr").first().hide();
$el.find("tr").first().fadeIn();
if ($el.find("tbody tr").length > 20) {
$el.find("tbody tr").last().fadeOut(400, function() {
$(this).remove();
});
}
slimScrollUpdate($el.parents(".scrollable"));
setTimeout(function() {
randomFeed();
}, 3000);
}
BTW, this code in it's state is very bad. It changes the DOM every time to show new feed element. It is better to render all elements whith display:none and only toggle visibility of actual one. It is common pattern

Try this:
news = new Array('news1','news2','news3','news4','news5','news6')
// option 1
news.sort(function() {
return .5 - Math.random();
});
//news = news1,news2,news3,news6,news4,news5
//option 2
len = news.length,
randomNumber = Math.floor((Math.random() * len) + 0);
// randomNumber = 3
part = news.slice(randomNumber, len)
// part = arrnews6,news4,news5
Please be more precise what are you expecting/about what your goal is!

Related

Continuously fade in and out random pictures

I am trying to get make a function that will continuously fade in and out pictures that are randomly selected, so that the same picture doesn't come up twice. I can get it to fade out / change image / fade in once if it is clicked with
$("img").click(function() { CODE });
but I have to click the image each time, and I am getting stuck trying to make it into a function that is called when the page has loaded:
$(document).ready(function() {
$("img").fadeOut(2000, function() {
while (picPicker1 === picPicker2) {
picPicker2 = (Math.floor(Math.random() * 5) - 1);
}
var source = pics[picPicker2];
$("img").attr("src", source);
$("img").fadeIn(2000);
picPicker1 = picPicker2;
});
});
pics[] is an array with the web addresses of five different pictures. I also tried using setInterval, but that didn't work either. New to all of these languages so thank you in advance for your patience!
setInterval was the correct function to use. The code you've provided in your question is missing a closing });.
Here's some basic code that makes use of setInterval to change the image:
JQuery:
var pics = [
"https://placehold.it/350x150/ff0000",
"https://placehold.it/350x150/00ff00",
"https://placehold.it/350x150/0000ff",
"https://placehold.it/350x150/F2F5A9",
"https://placehold.it/350x150/FF00FF",
];
setInterval(function() {
var picPicker2 = (Math.floor(Math.random() * 5) + 1);
var source = pics[picPicker2];
$("img").fadeOut(500).attr("src", source).fadeIn(500);
}, 2000);
Note: The images will repeat occasionally, but the code I've provided is only a base for you to improve upon.
Fiddle Demo
You can either use setInterval(), for (x = 5; x > 0; x ++) {}, var x = 0; do {} while (x = 0);, or var x = 0; while (x = 0) {}.
$(document).ready(function() {
var picPicker, source;
function generateImage() {
$("img").fadeOut(2000, function() {
picPicker = (Math.floor(Math.random() * 200));
source = 'https://unsplash.it/400/300/?image=' + picPicker;
$("img").attr("src", source);
$("img").fadeIn(2000);
});
setTimeout(generateImage, 5000);
}
generateImage();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="https://unsplash.it/400/300/?image=1">

Selecting random div for auto fade in and fade out

Currently, this code is auto fade in and fade out div by selecting the div element the way they were arranged (consecutive order). What I want to do now is to make the selector in random, I want to fade in a random div and after fading it out it will pick another random div and infinite loop the process. Since I'm new in jQuery and so confused, I also want to know your opinion on how to put this such process on a If Else statement in the easiest way. Like for example, I will get the value of a number
int num = 1;
If(num == 1){
<!-- Do the process-->
}
Else {
<!-- Do another process by selecting from another set of divs-->
}
Here is the code:
jQuery.fn.nextOrFirst = function (selector) {
var next = this.next(selector);
return (next.length) ? next : this.prevAll(selector).last();
}
$(document).ready(function () {
$('div.mb').fadeOut(500);
var fadeInTime = 1000;
var intervaltime = 3000;
setTimeout(function () {
fadeMe($('div.mb').first());
}, intervaltime);
function fadeMe(div) {
div.fadeIn(fadeInTime, function () {
div.fadeOut(fadeInTime);
setTimeout(function () {
fadeMe(div.nextOrFirst());
}, intervaltime);
});
}
});
Divs:
<div class="boxes">
<div class="mb one">1-------------one</div>
<div class="mb two">2-------------two</div>
<div class="mb three">3-------------three</div>
</div>
Not sure if this is exactly what you want but can be modified:
var mb = $('.mb'),
mbl = mb.length;
mb.hide();
rand();
function rand(){
var r = getRand(0, mbl);
mb.eq(r).fadeIn('slow', function(){
$(this).fadeOut('slow', function(){
setTimeout(rand, 200);
});
});
}
function getRand(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
Try changing the nextOrFirst function to something like:
jQuery.fn.nextOrFirst = function (selector) {
var xCount = selector.size();
return Math.floor(Math.random() * xCount ) + 1;
}
Instead of getting the next of first div, this gets a count of all of the divs,
and pics a random number between 1 and X(the number of divs with your selector)
Try something like this,Hope it helps
var c=$(".boxes div");
setInterval(function(){
$.each(c,function(a,z){
$("div[class='"+(z.className)+"'").fadeIn();
});
var item = c[Math.floor(Math.random()*c.length)];
var u=item.className;
$("."+u).fadeOut();
$("div[class='"+u+"'").fadeOut(1000);
}, 3000);
EDIT:
var c=$(".boxes div");
setInterval(function(){
$.each(c,function(a,z){
$("div[class='"+(z.className)+"'").hide();
});
var item = c[Math.floor(Math.random()*c.length)];
var u=item.className;
$("."+u).fadeOut();
$("div[class='"+u+"'").show().fadeIn(1000);
}, 2000);
FIDDLE LINK: https://jsfiddle.net/bv0jj4wp/29/

Resetting jquery varible to lowest possible value that doesn't exist

This script generate divs with cloud images that fly from left to right with random height and intervals. It generally works but it keeps incrementing divs "id" infinitely. I can't figure out how to reset the counter being safe that never two identical "id"s will exist in the same time.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
function cloud(type,time,nr){
$("#sky").append("<div id=\"cloudFL"+nr+"\" class=\"cloud"+type+"\" ></div>");
setTimeout(function() {
$("#cloudFL"+nr).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
var tx = 0;
setInterval(function(){
cloud(1,t1,nr);
nr++;
var n = $( "div.cloud1" ).length;
$( "span" ).text( "There are " + n +" n and "+ tx +" tx")
if(tx < n){tx = n}
else(tx = 1)
},500);
};
wave()};
cloudgenerator()
In the bottom, there is an instruction that checks if number of divs is starting to drop and presents those values in span for debugging.
Quick and easy solutionYou could loop through the id's in JQuery, starting from the lowest number, until you find a JQuery selector that yields 0 results...
var newid = 0;
var i = 1;
while(newid == 0) {
if( $('#cloudFL' + i).length == 0 ) { newid = i; }
else { i++; }
}
JSFIDDLE DEMO
Alternative solution (scalable)
Given that you may have many clouds onscreen at one time, you could try this alternative approach.
This approach creates an array of 'used ids' and the wave function then checks if any 'used ids' are available before creating a new id for the cloud function. This will run quite a bit more efficiently that then above 'quick fix solution' in situations where many clouds appear on screen.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
var spentids = [];
function cloud(type,time,id){
$("body").append('<div id="' + id + '" class="cloud' + type + '" >' + id + '</div>');
setTimeout(function() {
$('#'+id).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){
spentids.push( $(this).attr('id') );
$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
setInterval(function(){
if(spentids.length == 0) {
cloud(1,t1,"cloudFL" + nr);
nr++;
} else {
spentids = spentids.sort();
cloud(1,t1,spentids.shift());
}
},500);
};
wave()};
cloudgenerator()
JSFIDDLE DEMO - ALTERNATIVE
Why not get the timestamp and add this to your id?
If you donĀ“t need the ids i would stick to #hon2a and just add the styling to the class and remove the ids.
And another solution:
You could make a check if ID xyz is used. Like this e.g.
var cloudCount = jQuery('.cloud20000').length + jQuery('.cloud50000').length + 10;
for(var i = 0; i <= cloudCount; i++) {
if(jQuery('#cloudFL' + i).length <= 0) {
nr = i;
return false;
}
}
cloud(1,t1,nr);

Jquery function should also work with other elements

I'm trying to make this function working multiple times:
Currently works only with the h1 tag
how can I make it working for the <div class="logo"> as well? I don't want to repeat the function, I need a way to make the function working for various elements.
demo: http://jsfiddle.net/33Ec8/4/
JS:
// Get the divs that should change
function displayThese() {
var $heading = $('h1');
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 divs = displayThese();
var elem = divs.eq(Math.floor(Math.random() * divs.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
});
});
Your question isn't stated very clearly, so I would strongly suggest describing what the code should do vs what it does.
That said, here is a half-blind attempt at answering what I think you want.
You could pass in the selector as a parameter to displayThese.
function displayThese(selectorString)
{
var $elementsUnderWhichNothingShouldFade = $(selectorString);
...
}
then when you call displayThese, you can pass in any complex selector you like.
var divsToChange = displayThese('h1, div.logo')
Of course, you would need to add extra logic to test whether the image elements were underneath any of the resulting $elementsUnderWhichNothingShouldFade (which is a list of elements).

How can I stop a repeating function when the mouse is clicked?

I could really use some help. I have a javascript / jquery slider below that repeats over and over. I would like it to stop repeating when a specific button is clicked if possible. I am a complete novice and it took a lot to get to this point! Any help would be greatly appreciated.
$(document).ready(function () {
var i = 0;
var z = 0;
delay = 5000;
var el = $('#scroll-script');
var ql = $('#info-box');
var classesb = ['fp-info-one', 'fp-info-two', 'fp-info-three', 'fp-info-four'];
var classes = ['fp-slide-one', 'fp-slide-two', 'fp-slide-three', 'fp-slide-four'];
var interval = setInterval(function () {
el.removeClass().addClass(classes[i]);
i = (i + 1) % 4;
ql.removeClass().addClass(classesb[z]);
z = (z + 1) % 4;
}, delay);
});
$(document).ready(function () {
var i = 0;
var z = 0;
delay = 5000;
var el = $('#scroll-script');
var ql = $('#info-box');
var classesb = ['fp-info-one', 'fp-info-two', 'fp-info-three', 'fp-info-four'];
var classes = ['fp-slide-one', 'fp-slide-two', 'fp-slide-three', 'fp-slide-four'];
var interval = setInterval(function () {
el.removeClass().addClass(classes[i]);
i = (i + 1) % 4;
ql.removeClass().addClass(classesb[z]);
z = (z + 1) % 4;
}, delay);
// code that stop repeat
$('#your_button').on('click', function() {
clearInterval(interval );
});
});
As, you're using setInterval() for repeating time, so to clear that timer you need to use clearInterval()..
Note
#your_button will be replace with appropriate selector for your target button.
You just need to use clearInterval():
$(".somebutton").click(function()
{
clearInteval(interval);
interval=null;
});
i think clearInterval() help you to achieve this.
just apply this on click() event.
something like:
$('#element').click(function(){
clearInterval(Interval_OBJECT);
});
Use clearInterval(interval) when you want to stop the repeating action.
something like :
$('#btn').on('click', function(){ clearInterval(interval); });

Categories

Resources