3

How to addclass when div width is greater than 80% ? This is what I just tried

<div class="wrap_bar">
    <div class="bar" style="width:50%;"></div>
</div>
<div class="box"></div>


    <script>
                     var barTotal = $(".bar");
                     var box= $(".box");
                     var width = barTotal.width();
                     if (width > 80%)
                     box.addClass('type2')
    </script>

This code is not working well. Please help

sam
  • 99
  • 1
  • 11

4 Answers4

2

If you need this dimension detection only one time (when DOM loaded) then you can just following approach.

function addWhenResized(element){
    var parentWidth = $(element).parent().width();
    var elementWIdth = $(element).width();
    if( (elementWIdth / parentWidth)*100 > 79){
        $('.box').addClass('type2');
    } 
    else {
        $('.box').removeClass('type2');
    }
}

$(document).ready(function(){
    addWhenResized('.bar');
})

But main challenge will be there if you want detect the run time dimension change. Then need to take help from here: http://marcj.github.io/css-element-queries/

After added the plugins from above given link you should follow the following approach:

function addWhenResized(element){
    var parentWidth = $(element).parent().width();
    var elementWIdth = $(element).width();
    if( (elementWIdth / parentWidth)*100 > 79){
        $('.box').addClass('type2');
    } 
    else {
        $('.box').removeClass('type2');
    }
}

new ResizeSensor(jQuery('.bar'), function(){ 
    addWhenResized('.bar');
});
Hanif
  • 3,739
  • 1
  • 12
  • 18
0

Try this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
     var barTotal = $(".bar");
     var barTotalWidth = barTotal.width();
     var box= $(".box");
     var boxWidth = box.width();
     var widthPercent = boxWidth / barTotalWidth;
     console.log(widthPercent);
     if (widthPercent > 0.8)
     box.addClass('type2');
  });
                     
</script>

<div class="bar" style="width:200px;height:100px;background-color:red"> </div>
<div class="box" style="width:190px;height:80px;background-color:blue"> </div>


    
 
 
I. Ahmed
  • 2,438
  • 1
  • 12
  • 29
0

your codes don't work because you've just called javascript once when the page loaded , you have to wrap it into an event ! Take a look that answer

or that answer

-1
jQuery(document).ready(function($) {
if ($(this).width() > 768) {
    $('#service-1').addClass('row text-center');
 } else {
    $('#service-1').removeClass('row text-center');
 }
});

this will work fantastic when width is less than or more than will add or remove the class

sawan
  • 2,341
  • 3
  • 25
  • 51
Fernando
  • 11
  • 5