Reputation: 173
I have the function below:
var players = function(){
var $div = $('<div>').attr('id', 'prompt');
var $input = $('<input>').attr('class', 'player' + playerNames);
var $p = $('<p>').attr('class', 'player' + playerNames).html("Enter First Player" );
$div.append($input).append($p);
$('.container').append($div);
$('input').keydown(function(e) {
if(e.keyCode === 13) {
$div.addClass('move-left').removeAttr('id');
playerOne = $input.val();
$p.html($input.val())
$input.remove();
}
});
}
I want to call this function twice in a row.
I want the .addClass('move-left')
to be addClass('move-right')
playerNames which starts at 0 to be 1
and finally for the "Enter First Player" to be "Enter Second Player".
Do I need a for
?
if so does it have to wrap the entire function?
Thanks!
Upvotes: 0
Views: 75
Reputation: 809
What about passing those things as parameters to the function? And, perhaps instead of playerOne being closed over, make a local variable that you declare and return
var players = function(promptStr, classStr){
var $div = $('<div>').attr('id', 'prompt');
var $input = $('<input>').attr('class', 'player' + playerNames);
var $p = $('<p>').attr('class', 'player' + playerNames).html(promptStr );
$div.append($input).append($p);
$('.container').append($div);
var playerX = {name:null};
$('input').keydown(function(e) {
if(e.keyCode === 13) {
$div.addClass(classStr).removeAttr('id');
playerX.name = $input.val();
$p.html($input.val())
$input.remove();
}
});
return playerX;
}
var playerOne = players("Ready Player One", "move-left");
var playerTwo = players("Enter Player Two", "move-right");
Upvotes: 2
Reputation: 6332
With an if statement
$('input').keydown(function(e) {
if(e.keyCode === 13) {
if ($div.hasClass('move-left') {
$div.addClass('move-right').removeAttr('id');
} else {
$div.addClass('move-left').removeAttr('id');
}
playerOne = $input.val();
$p.html($input.val())
$input.remove();
}
});
Upvotes: 0