0

I am struggling to make this script working on Wordpress. On Fiddle it works well https://jsfiddle.net/xqxk2qdg/2/ Any idea why could I have this problem? It is properly enqueued and loaded on page.

var array = [];
var array1 = $('#input_8_3').val().split(',');
$("#input_8_3").val(array.join());

(function($){
$('div.thumbn').click(function() {
    var text = $(this).attr("id").replace('img-act-','');
  var oldtext = $('#input_8_3').val();
    if ($(this).hasClass('chosen-img'))
  {

    $('#input_8_3').val(text+oldtext);      
    var index = array.indexOf(text);
    if (index !== -1)
    {
        array.splice(index, 1);
    }

    array1.push(text);
    $(this).removeClass('chosen-img');
  }
  else
  {
    array.push(text);
    var index = array1.indexOf(text);
    if (index !== -1)
    {
        array1.splice(index, 1);
    }
    $(this).addClass('chosen-img');
  }
  $("#input_8_3").val(array.join());
  $("#input_8_4").val(array1.join());
  console.log(array1);
});
})(jQuery);
  • Your browser's error console should tell you what's wrong. – Milo Dec 8 '16 at 16:21
  • @Milo delete_attachment.js?ver=4.7:2 Uncaught TypeError: $ is not a function(…)(anonymous function) @ delete_attachment.js?ver=4.7:2 But still have no idea why. – Rafal Dec 8 '16 at 16:51
4

By default, jQuery runs in no conflict mode in WordPress. You have an anonymous function that passes the jQuery object so you can use it.

Your code will error on line two because it doesn't know what $ is. Move the first three lines into the anonymous function to resolve this.

(function($){
var array = [];
var array1 = $('#input_8_3').val().split(',');
$("#input_8_3").val(array.join());

$('div.thumbn').click(function() {
    var text = $(this).attr("id").replace('img-act-','');
  var oldtext = $('#input_8_3').val();
    if ($(this).hasClass('chosen-img'))
  {

    $('#input_8_3').val(text+oldtext);      
    var index = array.indexOf(text);
    if (index !== -1)
    {
        array.splice(index, 1);
    }

    array1.push(text);
    $(this).removeClass('chosen-img');
  }
  else
  {
    array.push(text);
    var index = array1.indexOf(text);
    if (index !== -1)
    {
        array1.splice(index, 1);
    }
    $(this).addClass('chosen-img');
  }
  $("#input_8_3").val(array.join());
  $("#input_8_4").val(array1.join());
  console.log(array1);
});
})(jQuery);
0
Uncaught TypeError: $ is not a function(…)

This is due to WordPress's interaction with jQuery.

A work-around is replacing instances of '$' with 'jQuery'

  • that is exactly what he was doing, just didn't do it 100% right – Mark Kaplun Dec 8 '16 at 19:20
0

This is what I use in my scripts file for jQuery functions. It should work in your case to.

    $(document).ready(function ($) { ... })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.