0

I've got some code from a developer that left our company. He wrote an inline function looking like this:

<button class="xxx" id="MyID" type="button" onclick="javascript: $('#openThis').slideToggle('slow');">btnText</button>

I've tried to remove this and put it in another function to write a callback so I can scroll to the toggled area when it's visible.

$("#MyID").click(function () {
    $("#openThis").slideToggle("slow");
});

But I can't seem to get it to work. What am I doing wrong?

  • 3
    Is the button dynamically created? – Satpal Jun 13 '17 at 09:47
  • 1
    Your code should work. Could you probably post a full snippet of your project? – Spitzbueb Jun 13 '17 at 09:49
  • 1
    Depending on the full situation here, [this may be appropriate reading](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). – James Thorpe Jun 13 '17 at 09:53

5 Answers5

2

are you adding the listener before or after the object is created on the DOM?

because if you are trying to bind that onclick function without waiting the document to be ready theres no object to create the listener.

something like this could work:

$(document).on('ready', function() {
  $("#MyID").click(function () {
    $("#openThis").slideToggle("slow");
  });
});
Sebastián Espinosa
  • 1,915
  • 11
  • 23
1

If you button is added dynamically then use on instead of click

Attach an event handler function for one or more events to the selected elements.

Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()

//Instead of document you can use a container id
$(document).on('click',"#MyID",function () {
    $("#openThis").slideToggle("slow");
});

What this approach does is it adds event to a currently selected element which is document here and it will delegate the event to your selector which is #MyID in this case.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

Nadir Laskar
  • 3,562
  • 2
  • 13
  • 29
0

$(document).on('click', '#myBtn', function(){
    $('#foo').slideToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="foo">content</div>
<button id="myBtn">Click me</button>
0

You want to scroll to the area so remove the JavaScript from the button

You need to do something like this

$("#MyID").click(function() {
    $('html, body').animate({
        scrollTop: $("#openThis").offset().top
    }, 2000);
    $("#openThis").slideToggle("slow");
});
edi
  • 665
  • 5
  • 14
-2

You should delete the onclick="" attributes in the button tag and in your javascript :

$("#MyID").click(function (e) {
  e.preventDefault();
    $("#openThis").slideToggle("slow");
});

Use the prevent default. Hope that help

Antonin Mrchd
  • 584
  • 1
  • 7
  • 25