click dynamic change width of div

by slawe

HTML

<div class="demo"></div>

CSS

.demo {
    width: 100px;
    height: 100px;
    background: red;
    -webkit-transition-property: width; /* Safari */
    -webkit-transition-duration: 1s; /* Safari */
    transition-property: width;
    transition-duration: 1s;
}

JavaScript

document.querySelector('.demo').addEventListener('click', function(e) {
    e.preventDefault();
    
    var current_width = parseFloat(this.offsetWidth, 10),
        new_width = 50,
        body_width  = document.getElementsByTagName('body')[0].offsetWidth;
    
    this.style.width = current_width + new_width + 'px';
    
    if (current_width + 50 >= body_width) {
    	this.style.width = 100 + 'px';
    }
}, false);