Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  25] [ 7]  / answers: 1 / hits: 19340  / 11 Years ago, sat, june 15, 2013, 12:00:00

I have 2 divs side by side and when one isn't there, I want the other to have a width of 100%.



while ($array = $query->fetch(PDO::FETCH_ASSOC)){    
if (!empty($array['photoname'])){
echo '<div class=photo></div>';
}
echo '<div class=info></div>';
}


Here's my Javascript/jQuery:



$(document).ready(function() {
//check if photo div exists
if ($('.photo').length){

}else{
$('.info').css('width', '100%');
}
});


So if there is no photo div I want the info div to get a width of 100%. How can I achieve this?



UPDATE



If I don't have any photo divs showing, the above works and sets info divs to 100%. But when I have a photo div anywhere on the page, then none of the info divs are set to 100% even if they dont have a photo div next to them.


More From » php

 Answers
52

You can use something like this:



HTML



<div class=main>
<div class=photo>a</div> <div class=info>a</div>
</div>


JS



$(document).ready(function() {
    //check if photo div exists
    $( .main ).each(function( index ) {
       var thisPhoto = $(this).find('.photo').html();
        if(thisPhoto==undefined){
            
            $(this).find('.info').css('width', '100%');
        }    
});
    
        
});


CSS



.main{
display:block;
color:red;
width:200px;
height:200px;
}
.photo{
float:left;
width:50%;
display:block;
background:red;
height:100%;
}
.info{
float:left;
width:50%;
display:block;
background:red;
height:100%;
}


DEMO



EDIT: Please see my updated jsfiddle, the reason why your jQuery is not working as expected is because you refer to class in a global score, as you want to modify your divs in a row basis you will have to somehow iterate trough each of them, this is when Jquery comes to the play again, in the updated code I'm using the find() function on each iteration, this will affect only the current row as the scope is reduced to the iterated element only.


[#77610] Thursday, June 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hallie

Total Points: 503
Total Questions: 114
Total Answers: 103

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
;