Rahul Menon
Rahul Menon

Reputation: 13

My javascript is not working (w jquery as well)

I am not able to get my javascript to work html:

<div id="tomato">
    <body>
        <button id="totato">total</button>
    </body>
</div>

javascript:

$(document).ready(function() {
  $("totato").click = potato();

  function potato() {
    $("tomato").css("background", "red");
  }
})

Upvotes: 0

Views: 27

Answers (3)

Rayon
Rayon

Reputation: 36609

You are missing #=> id selector

Event binding should be implement using .on() which will expect first argument as event and second argument will be function expression(callback function)

Note that you have parenthesis() around your function name which will invoke function when that line is executed.

$(document).ready(function() {
  $("#totato").on('click', potato);

  function potato() {
    $(this).css("background", "red");
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="tomato">

  <body>
    <button id="totato">total</button>
  </body>
</div>

OR

Use .click() which will expect argument as function expression(callback function)

$(document).ready(function() {
  $("#totato").click(potato);

  function potato() {
    $(this).css("background", "red");
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="tomato">

  <body>
    <button id="totato">total</button>
  </body>
</div>

Upvotes: 1

Matt
Matt

Reputation: 455

Put a # in front of your selectors in the javascript.

Upvotes: 0

miltone
miltone

Reputation: 4764

Your div#tomato must be IN the body tag. Not external body but internal body

Upvotes: 0

Related Questions