javascript - jQuery click function not working after get request -


i have been tackling code while now, , cannot click function work in jquery. want sidebar go away when click close image. when enter click function in console seem work. if put click function in complete function of request seems work.

javascript (doesn’t work):

'use strict';  $.get('http://api.ipify.org?format=text&callback=?',   function(text) {     $('input[name="user_ip"]').val(text);   } );  $('.close-trigger').click(function() {   $('aside.open').removeclass('open');   return false; }); 

javascript (works isn’t neat):

'use strict';  $.get('http://api.ipify.org?format=text&callback=?',   function(text) {     $('input[name="user_ip"]').val(text); $('.close-trigger').click(function() {   $('aside.open').removeclass('open');   return false; });   } ); 

sidebar html want hide:

<aside id="sidebar">       <h2>new proposal</h2>       <a href="#" class="close-trigger"><i class="fa fa-times fa-2x"></i></a>       <form id="proposal">         <div>           <label>project name</label>           <input name="project_name" type="text" required>         </div>         <div>           <label>project description</label>           <textarea name="project_desc" required>           </textarea>         </div>         <div>           <a href="#">upload photo</a>         </div>         <!--         <div id="details">           <span></span>, <span></span>         </div>         -->         <input type="text" name="user_ip" hidden>         <input type="submit" value="submit">       </form>     </aside> 

as said if paste click function on console while page running code works. not sure why doesn’t work on it’s own though. sorry being such specific question.

the problem html page downloaded , parsed synchronously. means if put script tag in head, script gets executed @ moment when body tag not yet available. reason, if attempt bind click event before aside part of html page rendered, not work - because there no aside in dom tree.

to workaround problem have several options. option number one, simplest. put <script> tag before closing </body> tag. way it's guarantied dom tree available binding events , dom manipulations. has downloaded , rendered.

option number 2 - listen either window.onload or domcontentloaded events. jquery have convenient shortcut this. wrapping code $(function() { ... }) subscribe domcontentloaded event. code becomes:

$(function() {     $.get('http://api.ipify.org?format=text&callback=?',       function(text) {         $('input[name="user_ip"]').val(text);       }     );      $('.close-trigger').click(function() {       $('aside.open').removeclass('open');       return false;     }); }); 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -