Denis Omerovic
Denis Omerovic

Reputation: 1440

How To Properly log content loaded via Ajax

I have a content loaded via Ajax, two divs and one list. Now Simply I want to when I type something in one of the divs and when I click on list item to just console.log which div I was typing on, and if I type on second one and click on list item to console.log that second one div. The problem is that I'm always getting the first one I clicked until I refresh the page.

Here is jsfiddle, this currently works as I want but it's a static content and I have a contant loaded via Ajax

https://jsfiddle.net/chille1987/rb5aqv9d/35/

$(document).on('input', '.reply-area, .comment-area', (e) => {
  currentElement = e.target;
  $('.list').show();

  $('.list li').click((e) => {
    e.stopImmediatePropagation();
    console.log(currentElement);
  })
})
div {
  border: 1px solid black;
  margin-bottom: 20px;
}

.list {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="reply-area" contenteditable="true"></div>
<div class="comment-area" contenteditable="true"></div>

<ul class="list">
  <li>First Child</li>
  <li>Second Child</li>
  <li>Third Child</li>
</ul>

<!-- This content is loaded via Ajax -->

Upvotes: 0

Views: 73

Answers (2)

Alex Stulov
Alex Stulov

Reputation: 110

You can store last input field class in the list data attribute. After input data updated. On list item click you get last updated input from this data field.

$(document).on('input', '.reply-area, .comment-area', (e) => {
  $('.list').show();
  $(".list").data('last-input', $(e.target).attr('class'));
});

$('.list li').click((event) => {
  event.stopImmediatePropagation();
  console.log($('.list').data('last-input'));
});

jsFiddle

Upvotes: 0

You have to move the li click event out of the input event.

var currentElement;
$(document).on('input', '.reply-area, .comment-area', (e) => {
  currentElement = e.target;
  $('.list').show();
})

$('.list li').click((e) => {
  e.stopImmediatePropagation();
  console.log(currentElement);
})

Demo

var currentElement;
$(document).on('input', '.reply-area, .comment-area', (e) => {
  currentElement = e.target;
  $('.list').show();
})

$('.list li').click((e) => {
  e.stopImmediatePropagation();
  console.log(currentElement);
})
div {
  border: 1px solid black;
  margin-bottom: 20px;
}

.list {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="reply-area" contenteditable="true"></div>
<div class="comment-area" contenteditable="true"></div>

<ul class="list">
  <li>First Child</li>
  <li>Second Child</li>
  <li>Third Child</li>
</ul>

<!-- This content is loaded via Ajax -->

Upvotes: 1

Related Questions