ipalibowhyte
ipalibowhyte

Reputation: 1563

Jquery Function not being called?

Please why on earth isn't the function being call I have spent close to an hour on this:

This is the jquery:

function toggleDivs() {
    var $inner = $("#inner");

    // See which <divs> should be animated in/out.
    if ($inner.position().left == 0) {
        $inner.animate({
            left: "-400px"
        });
    }
    else {
        $inner.animate({
            left: "0px"
        });
    }
}

$("button").bind("click", function() {
        alert("Hello");
    toggleDivs();
});

This is the head section in my html

<head>
<script type="text/javascript" src="PageScript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Lato:100,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="PageStyle.css">
</head>

Upvotes: 0

Views: 257

Answers (3)

Mr7-itsurdeveloper
Mr7-itsurdeveloper

Reputation: 1631

1)your code is working fine.

2) use ready function to use bind function

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="PageScript.js"></script>
      <script>

    function toggleDivs() {
    alert('hi');
    } 
    $( document ).ready(function() {
    $("button").bind("click", function() {
            alert("Hello");
        toggleDivs();
    });
     });  
        </script>

Upvotes: 2

Jeff Robert Dagala
Jeff Robert Dagala

Reputation: 633

Your head is incorrect. Kindly change the follow into this order:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="PageScript.js"></script>
    <link href='http://fonts.googleapis.com/css?family=Lato:100,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="PageStyle.css">
</head>

Explination:

Your PageScript.js will load first before the jquery.min.js because of this, all your jquery functions from your PageScript.js will cause an error.

Upvotes: 9

Sridhar R
Sridhar R

Reputation: 20418

Try with

$("button").on("click", function() {
        alert("Hello");
    toggleDivs();
});

If its dynamic button use event delegation

$(document).on("click",'button',function() {
        alert("Hello");
    toggleDivs();
});

Scripts order wrong.Jquery must first and then others

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="PageScript.js"></script>
    <link href='http://fonts.googleapis.com/css?family=Lato:100,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="PageStyle.css">
</head>

Upvotes: 1

Related Questions