I have a problem,
in Html
<div class="item ">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
in JS
var random = Math.floor(Math.random() * $('.item').length);
$('.item').hide().eq(random).show();
I need add class (no-active) of automatically and randomly in the div with class (item), but no for all divs. only some div.
Now my code only show 1 div, and it's not what I want.
you try this :
var random = Math.floor(Math.random() * $('.item').length);
var newrandom = 0;
//alert(random);
if(random==0){//alert(random);
$('.item').hide().eq(random).show();
}else if(random>0){
$('.item').hide();
for(var i=1; i<=random; i++){
newrandom = Math.floor(Math.random() * $('.item').length);
$('.item').eq(newrandom).show();
//alert(newrandom);
}
}
Using this u will get random no. for random times.
You can use each and toggleClass for that:
$(".item").each(function () {
$(this).toggleClass('no-active', Math.random() < 0.5);
});
.no-active { visibility: hidden }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item ">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
Related
http://prntscr.com/p9u6f9
I create random divs using:
let div1 = 'div_list';
let div2 = div1 + [Math.floor(Math.random()*24)];
node.setAttribute('id', div2);
And I want remove div using button, but how can I remove this, not having ID? Because the ID is random.
function remove() {
console.log(div);
let remove = document.getElementById(??????????);
remove.remove();
}
Add an eventListener upon the creation of the node and call remove with the generated id :
let div1 = "div_list";
let div2 = div1 + [Math.floor(Math.random() * 24)];
node.setAttribute("id", div2);
node.addEventListener("click", () => remove(div2)); // add the event listener for the button of deletion if you're creating it with the div
function remove(id) {
console.log(id);
let remove = document.getElementById(id);
remove.remove();
}
Just try this example, it's 100% working.
function randRemove() {
var divCount = 5;
var randNumber = Math.floor(Math.random() * divCount) + 1;
var randSelect = document.getElementById("div-" + randNumber);
randSelect.remove();
alert("Div Removed: " + "div-" + randNumber);
}
.just-style {
display: inline-block;
width: 300px;
height: 100px;
margin: 20px;
}
<button id="randRemove" onclick="randRemove()">Remove Random Div</button>
<div id="main-div">
<div id="div-1" class="just-style" style="background-color: red;"></div>
<div id="div-2" class="just-style" style="background-color: blue;"></div>
<div id="div-3" class="just-style" style="background-color: aqua;"></div>
<div id="div-4" class="just-style" style="background-color: violet;"></div>
<div id="div-5" class="just-style" style="background-color: forestgreen;"></div>
<!--AND MORE DIV ... -->
</div>
Enjoy and good luck =D
I have an object (div) which has four elements (with classes) inside.
Task: When height of the element A is lower than 40px then add to element B 20px margin-top.
However there are many objects on the page.
<div class="list">
<div class="block">
<div class="list-name" style="height: 20px">element A</div>
<div class="div1">another div here</div>
<div class="div2">another div here</div>
<div class="product-image-container">element B</div>
</div>
<div class="block">
<div class="list-name" style="height: 50px">element A</div>
<div class="div1">another div here</div>
<div class="div2">another div here</div>
<div class="product-image-container">element B</div>
</div>
(...)
</div>
Sorry, I tried this so far. However it works only if there are only two elements in the div.
$(document).ready(function(){
$('.list-name').each(function(index, obj){
console.log($(obj).height())
if($(obj).height() < 40)
{
$(obj).next('.product-image-container').css('margin-top', 20)
}
});
});
Thanks for any help.
Rob
As far as I understand, you need something like this:
var heightA = $(".list-name").css("height"); //get height of element. E.g. "20px"
heightA = heightA.substr(0, heightA.length - 2); //remove "px" from string => "20"
if (heightA < 40) { //if the height is less than 40
$(".product-image-container").css("margin-top", "20px"); //add margin-top 20px
}
To do this for all elements, you will need a for. Maybe try this:
var elements = $("body div").length; //get amount of divs. In the HTML you provided 'body' is the parent
for (i = 0; i < elements; i++) { //loop 'em all
var heightA = $("div:nth-child(" + i + ") .list-name").css("height"); //again get height of corresponding element
heightA = heightA.substr(0, heightA.length - 2); //remove "px"
if (heightA < 40) {
$("div:nth-child(" + i + ") .product-image-container").css("margin-top", "20px"); //set margin-top of corresponding element
}
}
I am creating a simple game that has 9 divisions and each 8 of the divisions have a penguin hidden in them and the 9th one has a monster. Now my game works fine but what I want to do is every time I load the page, arrangement of the divisions should change so as to add randomness to the game.
Here is my code:
$(document).ready(function() {
//This code will run after your page loads
$('body').on('mousedown', '.yeti', function(event) {
alert("Yaaaarrrr!");
});
});
<div class="gameholder">
<div class="title"></div>
<div class="penguin1"></div>
<div class="penguin2"></div>
<div class="penguin3"></div>
<div class="penguin4"></div>
<div class="penguin5"></div>
<div class="penguin6"></div>
<div class="penguin7"></div>
<div class="penguin8"></div>
<div class="yeti"></div>
</div>
After adding images and some positioning to the div's this is how it looks
Keeping Your Animals Contained
Consider creating a container for all of your game elements as you only want to randomize their order as you don't want to get the title mixed up in all of this :
<div class='game-container'>
<div class="penguin1"></div>
<div class="penguin2"></div>
<div class="penguin3"></div>
<div class="penguin4"></div>
<div class="penguin5"></div>
<div class="penguin6"></div>
<div class="penguin7"></div>
<div class="penguin8"></div>
<div class="yeti">
</div>
Shuffling Them Around
This should make them easier to randomize through a simple jQuery extension function like this one mentioned in this related thread :
$.fn.randomize = function(selector){
(selector ? this.find(selector) : this).parent().each(function(){
$(this).children(selector).sort(function(){
return Math.random() - 0.5;
}).detach().appendTo(this);
});
return this;
};
You can combine these two approaches by then simply calling the following when your page has loaded :
$(document).ready(function(){
// Define your randomize function here
// Randomize all of the elements in your container
$('.game-container').randomize('div');
});
Example
$.fn.randomize = function(selector){
(selector ? this.find(selector) : this).parent().each(function(){
$(this).children(selector).sort(function(){
return Math.random() - 0.5;
}).detach().appendTo(this);
});
return this;
};
// Randomize all of the <div> elements in your container
$(".game-container").randomize('div');
.game-container { width: 300px; }
.penguin { background: url('http://vignette1.wikia.nocookie.net/farmville/images/b/be/Baby_Penguin-icon.png/revision/latest?cb=20110103080900'); height: 100px; width: 100px; display: inline-block; }
.yeti { background: url('http://www.badeggsonline.com/beo2-forum/images/avatars/Yeti.png?dateline=1401638613'); height: 100px; width: 100px; display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class='game-container'>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='yeti'></div>
<div class='penguin'></div>
</div>
<body>
<div class="gameholder">
<div class="title"></div>
<div class="penguin1"></div>
<div class="penguin2"></div>
<div class="penguin3"></div>
<div class="penguin4"></div>
<div class="penguin5"></div>
<div class="penguin6"></div>
<div class="penguin7"></div>
<div class="penguin8"></div>
<div class="yeti"></div>
</div>
<script type="text/javascript">
$(document).ready( function() {
$('.gameholder div').shuffle();
/*
* Shuffle jQuery array of elements - see Fisher-Yates algorithm
*/
jQuery.fn.shuffle = function () {
var j;
for (var i = 0; i < this.length; i++) {
j = Math.floor(Math.random() * this.length);
$(this[i]).before($(this[j]));
}
return this;
};
//This code will run after your page loads
$('body').on('mousedown', '.yeti', function(event) {
alert("Yaaaarrrr!");
});
});
</script>
Here you would like to know what this 2 line of code is doing ->
j = Math.floor(Math.random() * this.length); // (1)
$(this[i]).before($(this[j])); // (2)
Here in line 1 first I am getting random number using Math.random, Math.random gives you floating number ranging from zero to one. so here I am multiplying that number with length, so it gives me random floating number from zero to length, now I am flooring this number to integer, to get integer from zero to length - 1
If we have a selector $('#b').before('#a') then it puts #a element before #b element, so here we are getting one by one element and putting them in the random order.
I'm trying to develop a very simple carousel with Pure Javascript and CSS. I'm having trouble with the "next" and "previous" button, since they should communicate the with each other, setting the current position of the carousel.
Here is my current code (or JsFiddle: https://jsfiddle.net/kbumjLw2/1/):
// Slider
var listRecommendations = document.getElementById('list-recommendations');
listRecommendations.style.left = 0;
// Previous button
document.getElementById("btn-prev").onclick = function() {
// Making sure this functions will not run if it's the 0px of the slider
if (parseInt(listRecommendations.style.left) != 0) {
var currentPosition = parseInt(listRecommendations.style.left) + 100;
listRecommendations.style.left = currentPosition + 'px';
console.log(currentPosition);
};
}
// Next button
var num = 100;
var maxValue = 1000 + 120;
console.log(maxValue);
document.getElementById("btn-next").onclick = function() {
if (num < maxValue) {
num += 100;
listRecommendations.style.left = '-' + num + 'px';
console.log(num);
};
}
#list-recomendations{
position: absolute;
}
.wrap-items .item{
float: left;
}
<div class="recommendation">
<div id="slider">
<div id="list-recommendations" class="wrap-items">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>
</div>
<!-- Slider controls -->
<button id="btn-prev" class="btn-slider prev">Previous</button>
<button id="btn-next" class="btn-slider next" title="Ver mais sugestões">Next</button>
</div>
As you can see on the console, the next button increases "100" at each click, and the previous button decreases "100" at each click. The previous button seems to be working fine, but the next button don't get the updated value, it always increase using the latest value it used.
Expected result:
Next button clicked: 100 > 200 > 300...
Prev button clicked: 200 > 100 > 0...
Next button clicked: 100 > 200 > 300...
Current result:
Next button clicked: 100 > 200 > 300...
Prev button clicked: 200 > 100 > 0...
Next button clicked: 400 > 500 > 600...
Any idea on what may be causing this issue?
check this updated fiddle
// Previous button
document.getElementById("btn-prev").onclick = function() {
// Making sure this functions will not run if it's the 0px of the slider
var currentPosition = parseInt(listRecommendations.style.left) - 100;
listRecommendations.style.left = currentPosition + 'px';
console.log(currentPosition);
}
// Next button
var num = 100;
var maxValue = 1000 + 120;
console.log(maxValue);
document.getElementById("btn-next").onclick = function() {
if (num < maxValue) {
var currentPosition = parseInt(listRecommendations.style.left) + 100;
num = currentPosition;
listRecommendations.style.left = num + 'px';
console.log(num);
};
}
you basically need to take the left value each time and do plus (+ next) minus (- prev) on it.
There is no use of num as you can play with the current position of the element.
Also note, - will concatenate the - symbol the the value, it will not subtract the value.
Ty this:
var maxValue = 1000 + 120;
var listRecommendations = document.getElementById('list-recommendations');
listRecommendations.style.left = 0;
document.getElementById("btn-prev").onclick = function() {
var val = parseInt(listRecommendations.style.left);
if (val != 0) {
val -= 100;
listRecommendations.style.left = val + 'px';
console.log(val);
};
}
document.getElementById("btn-next").onclick = function() {
var val = parseInt(listRecommendations.style.left);
if (val < maxValue) {
val += 100;
listRecommendations.style.left = val + 'px';
console.log(val);
};
}
#list-recomendations {
position: absolute;
}
.wrap-items .item {
float: left;
}
<div class="recommendation">
<div id="slider">
<div id="list-recommendations" class="wrap-items">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>
</div>
<!-- Slider controls -->
<button id="btn-prev" class="btn-slider prev">Previous</button>
<button id="btn-next" class="btn-slider next" title="Ver mais sugestões">Next</button>
</div>
Fiddle here
I am using this code to move images randomly in an area. But I need to show atleast 3 images always. Here is what I had done:
HTML
<div class="fade">Image 1</div>
<div class="fade">Image 2</div>
<div class="fade">Image 3</div>
<div class="fade">Image 4</div>
<div class="fade">Image 5</div>
<div class="fade">Image 6</div>
jQuery
(function fadeInDiv() {
var divs = jQuery('.fade');
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.fadeIn(Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.fadeOut(Math.floor(Math.random() * 1000), function() {
elem.before('<div> </div>');
fadeInDiv();
});
}
})();
This code fadein and fadeout images randomly as a result show 2 images at a time sometimes 1 image at a time sometime 3. I need to show 3 images with in 6 images every time with fadein fadeout functionality.
Here is how my home page look like:
Image1 Image2
Image3
I want it to look like:
Image1
Image2 Image3
or
Image1
Image2 Image3
or any other pattern with this images
you need to use css properties to change their position on the screen.
You ll have to precise their positionning style, IE absolute.
elem.css('top','15px') and elem.css('left','15px') are the propers method to move objects on screen. You ll adjust the 15px to the value you ll need. It s relative to the top-left corner of your screen.
fadeIn / fadeOut only change opacity property of those objects on the screen.
Try a recursive algorithm with delay lengths depending on the random order of the objects:
window.refresh = function(delay) {
delay *= 1000;
var doms = [];
var randos = [];
var index = 0;
function fadeout() {
if (index < 3) {
var random = $(doms.get(randos[index]));
$(random).delay(delay + 200 * index).fadeTo(200, 0, function() {
$(random).css("visibility", "hidden");
});
doms = doms.not(random);
index++;
fadeout(doms);
}
}
doms = $('.grid-item');
doms.css("visibility","visible");
doms.css("opacity","1");
var num = Math.floor(Math.random() * doms.length);
for (var i = 0; i < doms.length; i++) {
while (randos.indexOf(num) > -1) {
num = Math.floor(Math.random() * doms.length);
}
randos.push(num);
}
fadeout();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid">
<div class="grid-item">Image 1</div>
<div class="grid-item">Image 2</div>
<div class="grid-item">Image 3</div>
<div class="grid-item">Image 4</div>
<div class="grid-item">Image 5</div>
<div class="grid-item">Image 6</div>
</div>
<br>
<button onclick="refresh(0)">Trigger Animation</button>
<br>
<br>
<input type="number" placeholder="Time in Seconds">
<button onclick="refresh($(this).prev().val())">Trigger Delayed Animation</button>