I can’t find the problem. Why is this code making many copies of the “X”-button when I close the red-layer and when I click the first button again?
I thought the init worked like a proper constructor that just runs one time, right?
Here is a jsfiddle illustrating the problem:
http://jsfiddle.net/yoniGeek/mWghr/
Thanks for your time!
Y/
the html:
<div class="Main">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Phasellus non nisl mauris. Phasellus eget viverra mi.
Curabitur elementum tristique nibh, et faucibus eros
fermentum ut. Pellentesque non nisi augue.
Nulla facilisis ultrices malesuada. Sed bibendum lacus
sed lorem auctor rutrum.
iam semper justo id diam
</p>
<p id="last_child" > Lorem ipsum dolor
sit amet, consectetur adipiscing elit.
Phasellus non nisl mauris. Phasellus eget viverra mi.
Curabitut interdum velit ultricies.
</p>
<div id="layer_on" ></div>
</div>
the jquery-code:
(function(){
$('html').addClass('js');
//var red_layer;
var red_layer = {
red_box: $('#layer_on'),
init: function() {
$('<button></button>', {
text: 'push me'
}).insertAfter('.Main #last_child').on('click', this.show);
},
show: function() {
red_layer.close.call(red_layer.red_box);
red_layer.red_box.show();
},
close: function() {
var $this = $(this);
$('<span class="close">X</span>').prependTo(this).on('click', function() {
$this.hide();
});
}
//anonymous function
}; // red_layer object ends
red_layer.init(); //We call it back (the function )
})();
Why don’t you add the close button in the
initmethod? You only need to add the button once. As it is, you are adding theXbutton every time you show the box. Every time you clickpush me, you callshow(), which in turn calls.close(), which prepends anotherXto the box. Instead, call close from yourinitfunction:Demo: http://jsfiddle.net/xwmVr/
I would argue that your
closemethod doesn’t need to be a method. It simply adds theXbutton, which seems like a one-time thing. It also is not obvious what it is doing. It seems like callingclosewould actually close the box, but it doesn’t in this case.