0

Div layout using Javascript

If i click on + it should be open and it again click on - it should be close it is working fine but what i need to is that if there are more div how to handle them on run time.

<html>
<head>
<script src="jquery-1.7.1.js"></script>
<script src="script.js"></script>

<style type="text/css">
#widnow{
width:100%;
border:solid 1px;
    float:left;
}

#title_bar{
background: #FEFEFE;
height: 25px;
width: 100%;
}
#button{
border:solid 1px;
width: 25px;
height: 23px;
float:right;
cursor:pointer;
}
.box{
height: 50%;
 width: 50%;
background: #DFDFDF;
float:left;
}
#title_bar1{
background: #FEFEFE;
height: 25px;
width: 100%;
}
#button1{
border:solid 1px;
width: 25px;
height: 23px;
float:right;
cursor:pointer;
}
.box1{
height: 50%;
width: 50%;
background:#C0C0C0;
float:left;
}

</style>
</head>
<body>

<div id="widnow">

<div class="box" >
<div id="title_bar">

        <div id="button">+</div>
</div>
</div>
<div  class="box1">
    <div id="title_bar1">
            <div id="button1">-</div>
    </div>
</div>
</div>

</body>

</html>

script.js

  jQuery().ready(function() {

$("#button").click(function(){
if($(this).html() == "-"){
    $(this).html("+");
    $( ".box" ).css( "width","50%" );
    $( ".box1" ).show();

}
else{
    $(this).html("-");
    $( ".box" ).css( "width","100%" );
     $( ".box1" ).hide();
}

});


        });

Please come with idea that can help me solve the problem.

3 Answers 3

1

Don't hardcode the selector of the divs. This way you can expand it beyond a single div.

Use something like this:

$('button').on('click',function(){
    $(this).parent('div').css({'width' : '50%'});
});

Example

Sign up to request clarification or add additional context in comments.

Comments

0

Use relative paths/ e.g.

$(this).parent().css("width","50%");

So you always style the box that contains the (+/-) element that has been clicked.

You'll need to adapt your $(".box1") showing/hiding code, too; and as Pulkit said - you should use classes instead of ids. (select the child with the class ("box1") beneath the parent is:

$(this).parent().children("#box1")

Comments

0

Try giving a different id to each div element and also give the class and perform the jQuery function with id (#) instead of class (.)

1 Comment

how can i give id using javascript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.