Search code examples
javascripthtmlprototypejs

Prototype js make table resizable column


I am trying to make table columns resizeable using protoype js, found an solution using jquery here, but how to achieve the same using prototype js framework?

Jquery:

var pressed = false;
    var start = undefined;
    var startX, startWidth;

    $("table th").mousedown(function(e) {
        start = $(this);
        pressed = true;
        startX = e.pageX;
        startWidth = $(this).width();
        $(start).addClass("resizing");
    });

    $(document).mousemove(function(e) {
        if(pressed) {
            $(start).width(startWidth+(e.pageX-startX));
        }
    });

    $(document).mouseup(function() {
        if(pressed) {
            $(start).removeClass("resizing");
            pressed = false;
        }
    });

I tried same in Prototype:

var pressed = false;
var start = undefined;
var startX, startWidth;
Event.observe($('t1'), "mousedown",function(event){
    console.log('mousedown');
    start = $(this);
        pressed = true;
        startX = Event.pointerX(event);
        startWidth = $(event.srcElement).getWidth();
        $(start).addClassName("resizing");
});

Event.observe($('t1'), "mousemove",function(event){
    console.log('mousemove');
     if(pressed) {
       document.getElementById(start.id).style.width = ''+startWidth+(Event.pointerX(event)-startX)+'px';       
     }
});

Event.observe($('t1'), "mouseup",function(event){
    console.log('mouseup');
    if(pressed) {
            $(start).removeClassName("resizing");
            pressed = false;
        }
});

Width increases, but not properly. can anybody suggest what the problem is?


Solution

  • var pressed = false;
    var start, startX, startWidth;
    
    $$("table th").invoke('observe', 'mousedown', function(e) {
        start = $(this);
        pressed = true;
        startX = e.pageX;
        startWidth = start.getWidth();
        start.addClassName("resizing");
    });
    
    document.observe('mousemove', function(e) {
        if(pressed) {
            start.setStyle({width: startWidth+(e.pageX-startX) + 'px'});
        }
    });
    
    document.observe('mouseup', function() {
        if(pressed) {
            start.removeClassName("resizing");
            pressed = false;
        }
    });
    

    It's important to realize that Prototype was there first, and jQuery streamlined its API when they designed theirs. Also, since jQuery does everything with a "carrier" class, you have to keep doing $(this) over and over, while Prototype has permanently extended elements. Once you do $('some_id'), that element has all the extras of Prototype available to it.