Kishlin Kishlin - 1 year ago 37
Javascript Question

Add predefined html to a div with buttons

I'm trying to do a small piece of code that does the following : I have many groups of buttons plus a div, and clicking the buttons adds a predefined text to the matching div.

I put my code as an example here :


<button id="hey-0">hey</button>
<button id="hi-0">hi</button>
<button id="hello-0">hello</button>
<div id="text-0"></div>

<button id="hey-1">hey</button>
<button id="hi-1">hi</button>
<button id="hello-1">hello</button>
<div id="text-1"></div>

<button id="hey-2">hey</button>
<button id="hi-2">hi</button>
<button id="hello-2">hello</button>
<div id="text-2"></div>


$(document).ready(function() {

// Loops through all 3 groups
for (var i = 2; i >= 0; i--) {
// Gets the buttons and text block for this group.
var text = '#text-' + i;
var hey = '#hey-' + i;
var hi = '#hi-' + i;
var hello = '#hello-' + i;

// Add functions to the buttons.
$(hey).click(function(e) {

$(hi).click(function(e) {

$(hello).click(function(e) {


It almost works as I want it to, but it always adds the text to the first div and not the one corresponding to the buttons, because... reasons. Oo

So here are my questions :
First, why does finding the right button works, but not for the div (since all buttons work but it always adds the text to the first div).
Then, is there an even easier and faster way to do that? I'm pretty new to javascript and jquery so you'll have to speak like to a 3 year old to me.
I'm sure there is a way to get rid of the loop and use only one function that will say something like "for all (#/word/-/index/) buttons, make them add the /word/ to the html of the #text-/index/ div" but I have no clue how to do it.

Thanks a lot for your answers !

Answer Source

You can massively simplify your code by using DRY principles. Firstly put a common class on all the button elements, and use the value attribute to store the value to be placed in the related div. From there you can use a single event handler on that class which finds the related div and adds the value. Try this:

$('.btn').click(function() {
div {
  width: 300px;
  height: 40px;
  overflow-x: scroll;
  margin-bottom: 10px;
  background-color: #efefef;
  border: 1px solid black;
<script src=""></script>
<button class="btn" value="hey-0">hey</button>
<button class="btn" value="hi-0">hi</button>
<button class="btn" value="hello-0">hello</button>
<div class="text"></div>

<button class="btn" value="hey-1">hey</button>
<button class="btn" value="hi-1">hi</button>
<button class="btn" value="hello-1">hello</button>
<div class="text"></div>

<button class="btn" value="hey-2">hey</button>
<button class="btn" value="hi-2">hi</button>
<button class="btn" value="hello-2">hello</button>
<div class="text"></div>