How to capture data from div by click

event capturing
addeventlistener
trigger parent click event when child is clicked
how to capture button click event in javascript
how to stop event bubbling in javascript
event bubbling and capturing w3schools
how to stop event capturing in javascript
event bubbling w3schools

I would like to capture data from selected div(ie. name of country) by click and put in span , additionaly i want to find some way to mark selected divs, but also unmark others div which were selected previously.

https://codepen.io/tatasek/pen/PoojNGL

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="div div__first"></div>
    <div class="div div__second"></div>
    <div class="div div__third"></div>

    <p>I have selected:<span class="selectedCountry"></span></p>
    <script src="app.js"></script>
</body>
</html>

CSS

body{
    display: flex;
    height: 100vh;
    justify-content: center;
    align-items: center;;
}

.div{
    margin-left: 10px;
    padding: 3px;
    border: 2px solid black;
    background-color: skyblue;
    cursor: pointer;
}

p{
    margin-left: 10px;;
}
.active{
  background-color: yellow;
}

JS

const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');

divList.forEach(function(div, index){
    div.textContent = countries[index];

})

Thanks for your time! Michal

Building on what you've done so far, I just added some event listeners to check for changes and add the selected items to the list. Let me know if you need any further clarification.

const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');

divList.forEach(function(div, index){
div.textContent = countries[index];
div.addEventListener('click', function(){
  divList.forEach(function(el, i) {
    el.classList.remove('active')
  })
  this.classList.toggle('active');
})

})



var choices = document.getElementsByTagName('div')

for(var i = 0; i < choices.length; i++) {
  choices[i].addEventListener('click', function() {
     document.getElementsByClassName('selectedCountry')[0].innerText = 
document.getElementsByClassName('active')[0].innerText;



  })
}
body{
    display: flex;
    height: 100vh;
    justify-content: center;
    align-items: center;
}

.div{
    margin-left: 10px;
    padding: 15px;
    border: 2px solid black;
    background-color: skyblue;
    cursor: pointer;
}

p{
    margin-left: 10px;
}

.active{
  background-color: yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="div div__first"></div>
    <div class="div div__second"></div>
    <div class="div div__third"></div>

    <p>I have selected:<span class="selectedCountry"></span></p>
    <script src="app.js"></script>
</body>
</html>

Capture a click on a div, you can use ev.stopPropagation(); so the click doesn't pass to the parent div. $(". parent").on('click', function() { console.log('clicked on parent'); })  The code sets click handlers on every element in the document to see which ones are working. If you click on <p>, then the sequence is: HTML → BODY → FORM → DIV (capturing phase, the first listener): P (target phase, triggers two times, as we’ve set two listeners: capturing and bubbling)

Try

for (let i = 0; i < document.getElementsByClassName('div').length; i++) {
   document.getElementsByClassName('div')[i].addEventListener('click', appendToSpan, false);
}
function appendToSpan(e) {
   document.getElementsByClassName('selectedCountry')[0].innerText += e.target.innerText;
}

Edit:

Change to:

const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');

divList.forEach(function(div, index){
    div.textContent = countries[index];
    div.addEventListener('click', function() {
      this.classList.toggle('active');
      if (this.classList.contains('active')) {
         document.getElementsByClassName('selectedCountry')[0].classList.add(this.innerText);
      } else {
         document.getElementsByClassName('selectedCountry')[0].classList.remove(this.innerText);
      }
      let classes = document.getElementsByClassName('selectedCountry')[0].getAttribute('class').split(' ');
      document.getElementsByClassName('selectedCountry')[0].innerText = '';
      for (let i = 1; i < classes.length; i++) {
         document.getElementsByClassName('selectedCountry')[0].innerText += classes[i]
      }
    })
})

Bubbling and capturing, This handler is assigned to <div> , but also runs if you click any Also we can write our data into the event object in one handler and read it in  I am trying to capture data from the html after a click event happens. so when someone click on the view me button i am able to capture the name of the mortgage banker and the ID.

I've used addEventListener on click event on each div. Also I've created selected variable which is an array and keeps selected items. On click I check if the selected value is in selected variable by indexOf() function which returns -1 if there is not. Then I push() value to the array if it's not selected yet or delete it by splice() and index of value. Array is printed by join() function which concats each value of array,

const divList = document.querySelectorAll('.div');
const output = document.querySelector('.selectedCountry');
const countries = ['Lithuania', 'Latvia', 'Estonia'];
let selected = [];

divList.forEach((div, index) => {
    div.textContent = countries[index];
    div.addEventListener('click',()=> {
      var indexOfDiv = selected.indexOf(countries[index]);
      (indexOfDiv >= 0) 
        ? (selected.splice(indexOfDiv,1) && div.classList.remove('selected'))
        : (selected.push(div.textContent) && div.classList.add('selected'))
      output.textContent = selected.join(', ');
    });
});
.div { border: 1px solid lightgray; margin: 0.5rem; padding: 0.25rem 0.4rem; }
.div.selected { border-color: lightgreen; }
<div class="div div__first"></div>
<div class="div div__second"></div>
<div class="div div__third"></div>
<p>I have selected:<span class="selectedCountry"></span></p>

jQuery click() Method, Definition and Usage. The click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click  The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element. The has() method is used to return all the elements which match at least one of the elements passed to this method.

const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
const selectedCountry = document.getElementsByClassName('selectedCountry')[0];

function clearSelection() {
  divList.forEach(function(div) {
    div.classList.remove('active');
  })
}

divList.forEach(function(div, index){
    div.textContent = countries[index];
    div.addEventListener('click', function() {
      clearSelection();
      this.classList.add('active');
      selectedCountry.innerText = document.getElementsByClassName('active')[0].innerText;
    })
})
body{
    display: flex;
    height: 100vh;
    justify-content: center;
    align-items: center;
}

.div{
    margin-left: 10px;
    padding: 15px;
    border: 2px solid black;
    background-color: skyblue;
    cursor: pointer;
}

p{
    margin-left: 10px;
}

.active{
  background-color: yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="div"></div>
    <div class="div"></div>
    <div class="div"></div>

    <p>I have selected:<span class="selectedCountry"></span></p>
    <script src="app.js"></script>
</body>
</html>

.click(), An object containing data that will be passed to the event handler. The click event is sent to an element when the mouse pointer is over the element, and the   The setPointerCapture() method of the Element interface is used to designate a specific element as the capture target of future pointer events. Subsequent events for the pointer will be targeted at the capture element until capture is released (via Element.releasePointerCapture()).

.toggle(), A function to execute every odd time the element is clicked. handler. Type: Function( Event eventObject ). Additional handlers to cycle through after clicks. Note  Let’s instead capture this data so that we can use it elsewhere by writing it to a file. Writing the Data to a CSV File. Collecting data that only lives in a terminal window is not very useful. Comma-separated values (CSV) files allow us to store tabular data in plain text, and is a common format for spreadsheets and databases.

Introduction to events, The user clicking the mouse over a certain element or hovering the cursor over a You can gather from this (and from glancing at the MDN Event add specialist properties containing extra data that they need to function. $('body').on('click.hideMenu', callbackFunction); does the same thing as $('body').on('click', callbackFunction); jQuery allows us to namespace event handlers. This way if someone unbinds 'click' event on the body, it will not break our hideMenu handler. If we want to remove this we have to unbind 'click.hideMenu' handler directly.

The Dangers of Stopping Event Propagation, Unfortunately, clicking on "Remote Link" (which contains the data-remote attribute) doesn't close the In the “How to detect a click outside of an element? Take a snapshot to copy words or images from all or part of your PC screen. Use Snipping Tool to make changes or notes, then save, and share. Windows 10 has another screenshot app you might also like to try.

Comments
  • Thanks for yoru help mate i will review this code tomorrow cuz im a little bit exhausted and i will let u know
  • If you click on 'Run code snippet' you can see it in action without having to plug it in to your code.
  • Hey why did you put here attribute "i" in the bracekts? ` divList.forEach(function(el, i) { el.classList.remove('active') }) `
  • Hey, sorry, I just realized I had that in there. That isn't needed in this scenario. It's generally used to track the index of the iteration. I have a habit of adding it in case I ever need to use it.
  • Thanks, i works partaly ( it doesnt delete previously selected country and it is getting a little mess) but i will try to solve this problem. thanks btw do u have any solution for my second problem?
  • yes it has been tested in codepen-- works perfectly
  • Thanks man this is it! Frankly it is a tricky solution lol i thought it would be something a little bit simpler :D
  • Hey man this code is really good, its intuitive, but iam little bit puzzled. why did u use getElementsByClassname('selectedCountry)[0] instead of using querySelector('.selectedCountry') I think the second solution is even more easy to undesrtand than your. does it have any advantages over my solution? Thanks mate
  • @MichałSoja There are some differences (read more) but in this case it is not important what function you are using