0

If I click a box, I want to move x number of pixels for the scrollbar position and I want to append the box dynamically.

But when appending the box, the appended box does not have the click function listener dynamically added.

I already know how to apply jQuery on("click", function() function(){}) for dynamically added elements, but I am still confused about what my problem is all about.

$("#btn1").click(function(){  
    $("#viewContainer").append('<div class="page" id="">Text page</div>');
});


$("#viewContainer div").on("click", function() {
  $("#viewContainer div").removeClass("active");
  $(this).addClass("active");
  $("#viewContainer").scrollCenter(".active", 300);
    
});

jQuery.fn.scrollCenter = function(elem, speed) {
  var active = jQuery(this).find(elem); // find the active element
  var activeWidth = active.width() / 2; // get active width center

  var pos = active.position().left + activeWidth; //get left position of active li + center position
  var elpos = jQuery(this).scrollLeft(); // get current scroll position
  var elW = jQuery(this).width(); //get div width
  pos = pos + elpos - elW / 2; // for center position if you want adjust then change this

  jQuery(this).animate({
    scrollLeft: pos
  }, speed == undefined ? 1000 : speed);
  return this;
};
html,
body,
div {
  margin: 0;
  padding: 0;
}

.container {
  width: 800px;
}

#viewContainer {
  overflow-x: scroll;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
  white-space: nowrap;
  padding: 5px 0;
  height: 90px;
}

.page {
  text-align: center;
  width: 120px;
  height: 100%;
  border: 1px solid red;
  display: inline-block;
}

.active {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div style="width: 800px; float: left;">
<div class="container">
    <div id="viewContainer">
      <div class="page active" id="viewLeft2">I am very left.</div>
      <div class="page" id="">Text page</div>
      <div class="page" id="">Text page</div>
      <div class="page" id="">Text page</div>
      <div class="page" id="">Text page</div>
      <div class="page" id="">Text page</div>
    </div>
  </div>
  <div>
      <button id="btn1">Button</button>
  </div>
FSDford
  • 500
  • 4
  • 10
smsroql
  • 1
  • 2

0 Answers0