Dennis Offinga
Dennis Offinga

Reputation: 95

Getting divs next to each other when clicking on a button / JQuery

i am making a kind of storyboard where you can add and remove frames but i need to set divs next to each other, the code i now have it places the div's beneath each other. I want to make it with a loop Here is my code:

HTML

<div id="storyboard">
  <div id="container">
    <div class="frame">  
      <div class="frame__outer"> 
        <div class="frame__inner"></div>
        <div class="frame__content"></div>
        <div type="button" value="fade_in" class="add__button"> + </div>
      </div>
    </div>
  </div>
</div>

JS

_this.addClickFunction = function() {
  var i = 0;
  $('.add__button').click(function() {
      $('.frame').after('<div id="container'+(i++)+'"></div> <div class="frame__outer"> <div class="frame__inner"></div><div class="frame__content"></div></div>');
  });
};

Upvotes: 1

Views: 942

Answers (3)

Mamdouh Saeed
Mamdouh Saeed

Reputation: 2324

i need to set divs next to each other

Try this example to add new story container to all current .container

var i = 1;
$('.add__button').click(function() {
  i++;
  $(".container").each(function(x) {
    $(this).after('<div id="container' + x + '_' + i + '" class="container"><div class="frame"><div class="frame__outer"> <div class="frame__inner"></div><div class="frame__content">story ' + i + '</div></div></div></div>');
  });

});
.frame__outer {
  padding: 20px;
  background: #222;
  color: white;
  border-bottom: solid 3px green;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="storyboard">
  <input type='button' value='add story' class="add__button" />
  <div id="container" class='container'>
    <div class="frame">
      <div class="frame__outer">
        <div class="frame__inner"></div>
        <div class="frame__content">story 1</div>
      </div>
    </div>
  </div>
</div>

Upvotes: 1

Flyer53
Flyer53

Reputation: 764

If you want to arrange elements side by side which normaly are block elements and thus are positioned underneath eachother by default use either css floats or css flexbox.

Upvotes: 1

user5215301
user5215301

Reputation:

Use append() instead of after() function. This should work:

_this.addClickFunction = function() {
  var i = 0;
  $('.add__button').click(function() {
      $('.frame').append('<div id="container'+(i++)+'"></div> <div class="frame__outer"> <div class="frame__inner"></div><div class="frame__content"></div></div>');
  });
};

This works for keeping one .frame element and adding multiple divs to it of the structure:

<div class="container[i]">  
      <div class="frame__outer"> 
        <div class="frame__inner"></div>
        <div class="frame__content"></div>
      </div>
</div>

Upvotes: 2

Related Questions