user2144857
user2144857

Reputation:

About click events

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

Answers (3)

War10ck
War10ck

Reputation: 12508

There are a few steps you'll need to take in order to do this:

  1. On mouse down, create a node and place it in the document. In the example below, a span is created and placed within the div with id content.
  2. On mouse up, clear the container holding the new node of all content. In the example below, jQuery's .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();
    });
});

Fiddle

Upvotes: 0

adeneo
adeneo

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();
    }
});

FIDDLE

Upvotes: 5

megawac
megawac

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

Related Questions