Kamil
Kamil

Reputation: 1538

Attaching click event won't work

I've wanted to attach click event to an object not yet added to the DOM like here.

I've used a code from the answer but nothing happens when I click anything.

Here's my HTML:

<html>
<head>
<script src="resources/js/components/jquery/jquery-3.1.1.min.js"></script>
<script src="file.js"></script>
</head>
<body>
    <a href="#">asl;kdfjl</a>
    <div id="my-button">sdgdf</div>
</body>
</html>

JavaScripts are in those location and I can see them in Sources tab in Chrome.

My file.js has content exactly copy-pasted from jsfiddle:

$('body').on('click','a',function(e){
    e.preventDefault();
    createMyButton();
});

createMyButton = function(data) {    
    $('a').after('<div id="my-button">test</div>');        
};

$('body').on('click','#my-button',function (e) {
      alert("yeahhhh!!! but this doesn't work for me :(");
});

Upvotes: 1

Views: 125

Answers (2)

prasanth
prasanth

Reputation: 22490

Your code working with snippet .Better use with document.ready.Post you js after document.ready .And change the selector document instead of body

$(document).ready(function() {

  $(document).on('click', 'a', function(e) {
    e.preventDefault();
    createMyButton();
  });

  createMyButton = function(data) {
    $('a').after('<div id="my-button">test</div>');
  };

  $(document).on('click', '#my-button', function(e) {
    alert("yeahhhh!!! but this doesn't work for me :(");
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">asl;kdfjl</a>
<div id="my-button">sdgdf</div>

Upvotes: 0

MrCode
MrCode

Reputation: 64526

As your code is in the head tag, you need to use a DOM ready wrapper to ensure your code executes after the DOM has rendered elements.

The jsfiddle doesn't have it because the fiddle is set to run the code onload already.

$(function(){
    $('body').on('click','a',function(e){
        e.preventDefault();
        createMyButton();
    });

    createMyButton = function(data) {    
        $('a').after('<div id="my-button">test</div>');        
    };

    $('body').on('click','#my-button',function (e) {
         alert("yeahhhh!!! but this doesn't work for me :(");
    });
});

Upvotes: 1

Related Questions