Henry Gunawan
Henry Gunawan

Reputation: 942

Cannot call javascript function in wordpress

This might be basic, but this issue takes me hours to figure out and I haven't found any solutions for this. I am using Wordpress 3.5 and I have an external javascript file called general.js in this folder: wp-content/themes/[folder_name]/js. In general.js, I write a function called hideError, basically to hide error label that popped out from my textboxes.

(function($) {
function hideErrorLabel(i) {
    //codes for handling label
}
})(jQuery);

I called it like this:

<span class="component-wrapper" onmouseover="hideErrorLabel(0)">
    <input type="text" name="txtName" size="10" />
    <label for="txtName" class="error">All field must be filled.</label>
</span>

I pass a parameter because these textboxes are array. Strangely, it gives me javascript error "hideErrorLabel is not defined". What went wrong? Please help.

Upvotes: 1

Views: 4267

Answers (3)

Matt Whipple
Matt Whipple

Reputation: 7134

There are a couple reasons this could be happening, the safest answer which is not the simplest would be to move the event binding in to the code. You could also use delegation and you shouldn't need an index if you're just looking to scope the function. If you do need the index you could get the location implicitly or use a dataset value to explicitly provide one through PHP.

It sounds like you'd just need something like:

(function($) {
  $(function() {
    $(document).on('mouseover', '.component-wrapper', function(event) {
      var $wrapper = $(event.currentTarget);
      $wrapper.find('.error').hide();
    });
  });
})(jQuery);

But you could adapt it to call external functions or provide extra logic as needed.

Upvotes: 1

Sanchit
Sanchit

Reputation: 2260

Just remove the first and last line of that javascript code. You are hiding your function! Declare it openly in any script tag.

<script type="text/javascript>
function hideErrorLabel(i) {
  //codes for handling label
}
</script>

Upvotes: 1

Zeta
Zeta

Reputation: 105876

(function($) {
 /* code */
})(jQuery);

will ensure that the /* code */ you provided gets executed after the DOM has been parsed. However, this will prevent hideErrorLabel from being defined when the parser tries to interpet the onmouseover attribute.

In order to fix this you should use modify your event handlers also in the /* code */ section:

(function($) {
function hideErrorLabel(i) {
    //codes for handling label
}

$('.component-wrapper').on('mouseover',hideErrorlabel);
})(jQuery);

Upvotes: 2

Related Questions