Last active
August 29, 2015 14:03
-
-
Save crobinson42/20117599134799489e54 to your computer and use it in GitHub Desktop.
(jQuery) Edit Element in-place
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ****Copy and paste in script tags in an empty HTML page**** | |
// | |
// - When you click on a button it turns into an input field, | |
// - you can edit the text and press "enter" to switch back | |
// - to a button | |
// | |
$(document).on('ready', function() { | |
// Make buttons and append it to the DOM | |
$('body').prepend('<button class="button">This is a Button!</button>'); | |
$('body').prepend('<button class="button">Boom</button>'); | |
$('body').prepend('<button class="button">Another Button</button>'); | |
// Set a click listener on the buttons | |
$(document).on('click','.button',function(){ | |
// store reference to "owner object" | |
var $el = $(this); | |
// store jquery object for imput | |
var $input = $('<input type="text" name="input"/>'); | |
// set the input box text to existing button text | |
$input.val($el.text()); | |
// replace button with input element | |
$el.replaceWith($input); | |
// Set listener for keypress | |
$(document).on('keypress',function(e){ | |
// Check if "enter" key is pressed | |
if(e.which == 13) { | |
// store a jquery button object in variable | |
var $btn = $('<button class="button"></button>'); | |
// get the text from the input and set button text | |
$btn.text($('input').val()); | |
// replace input with button | |
$('input').replaceWith($btn); | |
} | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment