Gᴇᴏᴍᴇᴛᴇʀ
Gᴇᴏᴍᴇᴛᴇʀ

Reputation: 409

jQuery not loading on HTML

I got this code I'm wanting to use and it won't respond. I know the code it right because it's on jsfiddle: http://jsfiddle.net/User86745458/ztz4Lf23/

But when I copy-paste this code, it does nothing:

<!DOCTYPE HTML>    
<html>
<head>

        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>

        <script>$('button').click(function(){        
    $('textarea').text($('textarea').text() + $(this).text());
    //$('input:text').val($('textarea').text() );
    $('input:text').val($('input:text').val() + ' ' +  $(this).data('stuff'));
});

</script>

</head>
<body>

<button data-stuff='stuff_Q'>Q</button>
<button data-stuff='stuff_W'>W</button>
<button data-stuff='stuff_E'>E</button>
<button data-stuff='stuff_R'>R</button>
<button data-stuff='stuff_T'>T</button>
<button data-stuff='stuff_Y'>Y</button>
<br/><br/>  
<input type='text'/>
<br/><br/>  
<textarea></textarea>

</body>
</html>

I can't find a syntax error though. Thanks in advance

Upvotes: 0

Views: 44

Answers (3)

Lumi Lu
Lumi Lu

Reputation: 3305

Here http://learn.jquery.com/using-jquery-core/document-ready/ is good resource for this.

I would like to wrap your following js code into

$(function(){
  // Your js code
});

It would be something like this,

<script type='text/javascript'>
$(window).load(function(){
$('button').click(function(){        
    $('textarea').text($('textarea').text() + $(this).text());
    //$('input:text').val($('textarea').text() );
    $('input:text').val($('input:text').val() + ' ' + $(this).data('stuff'));
}); 
});    
</script>

Upvotes: 0

Jordan Honeycutt
Jordan Honeycutt

Reputation: 338

Interesting thing to remember: Code that manipulates the DOM needs to execute after the page finishes loading.

Funny thing about JSFiddle is it wraps all of your javscript in an onload listener by default. That's why it worked so well there but gave you trouble in the real world. You're not going crazy.

Upvotes: 1

James111
James111

Reputation: 15903

Put you Jquery Code into a $(document).ready(function() { });

Like so:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

        <script>


$(document).ready(function(){ 

   $('button').click(function(){        
        $('textarea').text($('textarea').text() + $(this).text());
        //$('input:text').val($('textarea').text() );
        $('input:text').val($('input:text').val() + ' ' +  $(this).data('stuff'));
    });
}); //End of document.ready
    
</script>

Upvotes: 0

Related Questions