-2

On my PHP project I have some comment box div that repeat it self, how ever every time I want some one who is clicking on it (the div itself), to change the width of the div to 100%, the problem comes here, whenever I try making something like this, it is changing all divs width and not individually to the specific box it self , is there any solution that comes up in your head?

s.f.b.h
  • 73
  • 1
  • 8

3 Answers3

2

Just set an ID to your div (if you want just to modify only one item in the whole webpage) and make reference to it from JQuery (as you have tagged it).

If you want to modify all the divs in which you click (but only the div in which you click will be changed each time) then you can refer to the class associated to each div.

$( document ).ready(function() {
    $(".div").click(function() {
      $(this).css("width", "100%");
    });
});
html,body{
  width: 100%;
  height: 100%;
}

.div{
  height: 100px;
  width: 100px;
  background-color: red;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1" class="div"></div>
<div id="id2" class="div"></div>

EDIT: If you want that they will be back to their initial position just do an if statement in your Javascript.

$( document ).ready(function() {
  $(".div").click(function() {
    if($(this).css("width") == "100px")
      $(this).css("width", "100%");
    else
      $(this).css("width", "100px");
  }); 
});
html,body{
  width: 100%;
  height: 100%;
}

.div{
  height: 100px;
  width: 100px;
  background-color: red;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1" class="div"></div>
<div id="id2" class="div"></div>
Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
0

You can use an unique identifier like id or class(apparently) or use event object to find out which DOM element is clicked

Using class

 //probable html
<div class = "abc"></div>
 <div class = "abc"></div>
 <div class = "abc"></div>

JS

$('.abc').click(function(){
     $(this). addClass('a class which will set to 100%') // or use .css
    })

Using Event object

 $('div').on('click',function(event){
   var _target = event.target;
    $(_target).addClass('class which will make it 100%')
})
brk
  • 48,835
  • 10
  • 56
  • 78
0

Add a class to the clicked div and define width of 100% for that class:

HTML:

<div class="comment">Comment 1</div>
<div class="comment">Comment 2</div>

jQuery:

$('.comment').on('click', function() {
    $('.activeComment').removeClass('activeComment');
    $(this).addClass('activeComment');
});

CSS:

.comment {width: 50%;}
.comment.activeComment {width: 100%;}

JSfiddle

Samurai
  • 3,724
  • 5
  • 27
  • 39