-1

I need to create few div elements after click the button. So I decide to make something like template in external file and append in head div tag using jquery.

$('.socket-element').on('click', function (e) {
$.ajax({
    url: '/my-site/tags/socket-box.php',
    success: function (data) { $('#room-place').append(data); },
    dataType: 'html'
    });
});

And my external html file:

<div class="socket-box room-box-element col-xs-2 ui-draggable ui-draggable-handle">
<div class="row">
    <div class="row">
        <div class="box-header col-xs-12">
            <div class="row">
                <div class="col-xs-2">
                    <img class="down-arrow" src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-right-b-128.png" width="14" height="18" />
                </div>
                <div class="col-xs-8">
                    <h6>Temperature</h6>
                </div>
                <div class="col-xs-2">
                    <img class="settings" src="https://cdn2.iconfinder.com/data/icons/flat-ui-icons-24-px/24/settings-24-128.png" width="18" height="18" />
                </div>
            </div>
        </div>
    </div>
</div>                  
<div class="row">
    <div class="row">
        <div class="box-content col-xs-12">
            <div class="row">
                Test
            </div>
        </div>
    </div>
</div>

So this code is working fine is add the external html on the original html file but when I need to use click event on appended html is not working. So I need to use few events like click, draggable from jquery ui etc.

But when I need to use: this click event then for appended html is not working

$('.down-arrow').click(function (e) {
    alert('Test');
});

How can I solve this problem.

evelikov92
  • 755
  • 3
  • 8
  • 30

4 Answers4

2

Try this :

$('.socket-element').on('click', function (e) {
$.ajax({
    url: '/my-site/tags/socket-box.php',
    success: function (data) {

     $('#room-place').append(data); 
     $('#room-place').ready(function(){
      $('.down-arrow').click(function (e) {
        alert('Test');
        });
     });
    },
    dataType: 'html'
    });
});

Hope this will help:)

AhmadReza Payan
  • 2,171
  • 1
  • 23
  • 33
1

For dynamic events do write using event delegation like:

$(document).on("click",".down-arrow",function(){
//write your code here
})
Shashank Sood
  • 480
  • 5
  • 16
1

Please Try to use the events inside the on ready function .. Trust me it will work properly.

$(document).ready(function(){
    $('.down-arrow').click(function (e) {
        alert('Test');
    });
});

Please try this way.

dimlucas
  • 5,040
  • 7
  • 37
  • 54
Pranav MS
  • 2,235
  • 2
  • 23
  • 50
0

Use event delegation

$(document).on('click', '.down-arrow',function(e){
});
Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21