Jquery: how to produce 1 of 3 phrases when event happens
I have a bookmarking feature on my site, when the person clicks a paragraph, the box that is already hovering over that paragraph that reads "bookmark this" inserts "sw开发者_如何学编程eet man" in place of "bookmark this". so 'bookmark this' disappears and "sweet man" takes its place, how would i make it so when i click on the paragraph, it places 1 of 3 random phrases in there, lets say the 3 phrases are "success", "sweet man", and "awesome". here's a little bit of my code to show you where the random phrase would be placed.
$('p').click(function (e) {
var offset = $(this).offset();
var top = offset.top
if ($('#placeBookmark').hasClass('placing')) {
$('#placeBookmark').trigger('click')
$('#bookmark').css({left: offset.left - 30, top: top}).show();
$('#bookmarkThis').html('***SWEET MAN.***').delay(1000).fadeOut(400, function(){
$(this).html('BOOKMARK THIS')
})
}
});
See where in my code it says "SWEET MAN.", that's where the 1 of 3 random phrases should be placed after the user clicks the paragraph.
THANK-YOU
$('p').click(function (e) {
var offset = $(this).offset();
var top = offset.top
// list of phrases
var phrases = ["success", "sweet man", "awesome"];
if ($('#placeBookmark').hasClass('placing')) {
$('#placeBookmark').trigger('click')
$('#bookmark').css({left: offset.left - 30, top: top}).show();
// Selects a random phrase from the list.
// Note that it doesn't require the length to be exactly three,
// you can add and remove phrases above without changing this line.
var selectedPhrase = phrases[Math.floor(Math.random() * phrases.length)];
$('#bookmarkThis').html(selectedPhrase).delay(1000).fadeOut(400, function(){
$(this).html('BOOKMARK THIS')
})
}
});
Edit
As a separate function:
var getRandomPhrase = function() {
var phrases = ["success", "sweet man", "awesome"];
return phrases[Math.floor(Math.random() * phrases.length)];
};
Or with the phrases are arguments:
var getRandomPhrase = function(phrases) {
return phrases[Math.floor(Math.random() * phrases.length)];
};
Use it like this:
...
$('#bookmarkThis').html(getRandomPhrase()).delay(1000).fadeOut(400, function(){
...
or, when phrases are used as arguments:
...
$('#bookmarkThis').html(getRandomPhrase(["success", "sweet man", "awesome"])).delay(1000).fadeOut(400, function(){
...
精彩评论