Reputation: 79
how to make a text randomly display at different locations in a page.
for instance:
I want the question marks blink randomly in the header. Is it possible through jquery?.
Upvotes: 0
Views: 108
Reputation: 14313
Yes this is possible. I'd recommend using Math.random
. Here's an example on how to do it:
maxNum = 30;
setTimeout(time,700);
function time() {
if ($('.qusetion').length > maxNum) {
return;
}
for (var i = 0; i < 30; i++) {
$("<div class='question'>?</div>")
.appendTo(".container")
.css({
"left" : $(".container").width() * Math.random(),
"top" : $(".container").height() * Math.random()
})
.fadeIn(500 * Math.random(), function () {
$(this).fadeOut(500 * Math.random(), function () {
$(this).remove();
});
});
}
setTimeout(time,500 * Math.random() + 100);
}
.question {
position:fixed;
display:none;
}
.container {
width:100px;
height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
Upvotes: 1
Reputation: 536
Yes that's possible. Here is the code:
var randomY = Math.random()*10000 % $('header').height(),
randomX = Math.random()*10000 % $('header').width();
$(document).ready(function(){
$('#question').css({
'top' : randomY,
'left': randomX
});
});
header{
height: 500px;
width: 100%;
position: relative;
}
#question{
position: absolute;
}
<header>
<span id="question">?</span>
</header>
Upvotes: 0
Reputation: 1479
Yes, I don't bring you the code but:
Javascript Math.random():
Math.random();
From 1 to 100 then u can use for % of width and height:
//returns math random from 1 to 100
Math.floor((Math.random() * 100) + 1);
Now you just miss declare some <span>
's (absolute positioned) contained in a 100%-100% sized component in your HTML and manage them with JQuery. One way (there are more):
$('#elementID').css('property': 'value');
Something like:
random = Math.floor((Math.random() * 100) + 1)
$('#span').css('top', random + '%');
$('#span').css('left', random + '%');
Upvotes: 0