Reputation:
This may have been asked already, so if it has, I apologize for the re-post, but I'm trying to get a button to append something to a document when a user pushes the mouse button down, then removes that something and returns to the original state when the user releases the mouse button. How do I get something like that to happen? Here's what I have so far.
var test = 'Hi';
$('#annun').on('mousedown', function(){
$('body').append(test);
});
$('#annun').mouseup(function(){
$(test).remove();
});
Upvotes: 0
Views: 42
Reputation: 12508
There are a few steps you'll need to take in order to do this:
.empty()
is called on the div with id content.The above steps create the desired effect. See the code below and checkout the accompanying fiddle.
HTML:
<button type="button">Show Hidden Content</button>
<div id="content"></div>
JavaScript:
$(function () {
var $content = $('#content');
$('button').off().on('mousedown', function () {
$('<span />', { text: "Argh! You found my hidden text!" }).appendTo($content);
}).on('mouseup', function () {
$content.empty();
});
});
Upvotes: 0
Reputation: 318342
You'll need an actual node, and not just a string. For just a plain textnode you can use the native method :
var test = document.createTextNode('Hi')
$('#annun').on({
mousedown: function(){
$('body').append(test);
},
mouseup: function(){
$(test).remove();
}
});
Upvotes: 5
Reputation: 11373
In your code you are adding a string to an element which jQuery will convert into a textNode
for you. The problem is jQuery will not know how to remove test when you call $(test).remove()
so either you have to make test
a textNode yourself or wrap it in an element. This will allow jQuery to interact with the textNode as it will have a correct reference.
Make test a textNode
var $test = $.parseHTML('Hi');//make textNode
Or make test an element
var $test = $('<span>Hi</span>');//make element
Then append/remove the jQuery reference to the DOM
$('#annun').one('mousedown', function(){
$('body').append($test);
})
.one('mouseup', function(){
$test.remove();
});
Upvotes: 0