Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery with html

My jQuery is not working, i don't know what am i doing wrong.

The button is supposed to hide the paragraph and bring it back when i press it.
Have put the html and toggle.js code.
I am referencing the jquery library from a folder called js.

HTML

<DOCTYPE = html>
<html lang = "en">
<head>
    <meta charset = "utf-8">
    <script src=  "js/jquery-1.6.2.js"></script>
    <script src = "js/toggle.js"></script>

    <title>Jquery Example</title>
</head>
<body>
    <input type = "button" value = "Hide" id = "toggle_message"/>
    <p id = "message">You can see this paragraph</p>
</body>
</html>

TOGGLE.JS

$('#toggle_message').click(function() {

  var value = $('#toggle_message').attr('value');
  $('#message').toggle('fast');

  if (value == 'Hide') {
    $('#toggle_message').attr('value', 'Show');
  } else if (value == 'Show') {
    $('#toggle_message').attr('value','Hide');
  }
});
like image 495
brayo Avatar asked Feb 11 '26 07:02

brayo


1 Answers

Try wrapping your code with $(function() {}); It likely can't access the DOM yet. e.g

$(function() {

    $('#toggle_message').click(function() {

      var value = $('#toggle_message').attr('value');
      $('#message').toggle('fast');

      if (value == 'Hide') {
        $('#toggle_message').attr('value', 'Show');
      } else if (value == 'Show') {
        $('#toggle_message').attr('value','Hide');
      }
    });
});
like image 184
cstruter Avatar answered Feb 13 '26 20:02

cstruter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!