John Smith
John Smith

Reputation: 6207

Putting body into a DIV kills the event

dont ask me why, but I want to put the whole body into a div, and shrink the content. I have this so far:

$('#newButton').click(function() {
    if ($('#xxxx').length == 0)
    {
        $('body').html('<div id="xxxx">'+$('body').html()+'</div>');
        $('#xxxx').css('background-color', 'red').css('overflow', 'scroll');
    }
    alert ($('#xxxx').width());
    $('#xxxx').width (parseInt($('#xxxx').width())-10+'px');
});

this is ok so far - but then this click() method never triggers again. For an unknown reason, its killed....

Upvotes: 0

Views: 61

Answers (3)

Blazemonger
Blazemonger

Reputation: 92953

You destroyed the original DOM element when you updated the .html(). Then you created a new element with the same ID, but no event handler. (Remember, HTML isn't the same as the DOM elements. When you remove and replace the HTML, whole new DOM elements are created from that code.)

You could solve this with event delegation:

$('document').on('click','#newButton',function() {

But I would use .wrapAll() instead:

if ($('#xxxx').length == 0) {
    $('body > *').wrapAll('<div id="xxxx">');

Upvotes: 3

John Smith
John Smith

Reputation: 6207

for those why I want it (it might be weird, but we programmers has to get used to weird solutions). I wanted to simplify to check the site with shrank windows, so with - and + you can decrease/increase the "window":

$(document).ready(function() {

var doResizing = function (increaseWith)
{
    if ($('#xxxx').length == 0)
    {
        $('body').css('margin', 0).css('padding', 0);
        $('body > *').wrapAll('<div id="xxxx" /></div>');
        $('#xxxx').css('background-color', 'red').css('overflow', 'scroll').css('padding', 0).css('margin', 0).css('position', 'absolute').width('100%');
    }
    $('#xxxx').height(parseInt($(window).height())+'px').width(parseInt($('#xxxx').width())+increaseWith+'px');
}

$(document).keypress(function(e) {
    if (e.which == 45) { doResizing (-10); }
    if (e.which == 43) { doResizing (+10); }
});

});

enjoy!

Upvotes: 0

Axel Amthor
Axel Amthor

Reputation: 11106

try this:

<style>
    #xxxx{ position: absolute; top: 0px; left: 0px; background: none; display: none; }
</style>

$('#newButton').click(function() {
    if ($('#xxxx').length == 0)
    {
        $('body').append('<div id="xxxx">'+$('body').html()+'</div>');
        $('#xxxx').css('background-color', 'red')
          .css('overflow', 'scroll')
          .css("display", "block";
    }
    alert ($('#xxxx').width());
    $('#xxxx').width (parseInt($('#xxxx').width())-10+'px');
});

this will copy a new "body" (actually it's a div with the same content) on top of the old body.

Upvotes: 1

Related Questions