-1

I am using this function on a wordpress site to move an html element after another html element.

    jQuery(document).ready(function($) {
       $(".promoted-products-box").insertAfter(".top-rated-prod-position"); 
    })

This function works fine, however i noticed when refreshing the page, it only works about 60% of the time.

I assume this issue is because the widget content ".promoted-products-box" has not fully loaded in yet. And sometimes the jQuery will run before this element is loaded on the page? That is what i am assuming.

So i was wondering if i could run the above script only once the ".promoted-products-box" element has been loaded on the page successfully. How would i do something like that?

Thanks for any help!

VeggieBot
  • 77
  • 6

1 Answers1

1

What you’re looking for is

$(document).ready(function() {
    # insert your code here
 });

The code inserted will run after DOM is loaded

Reference: http://learn.jquery.com/using-jquery-core/document-ready/

Jose Rojas
  • 46
  • 2
  • 3
  • This is my current code: jQuery(document).ready(function($) { $(".promoted-products-box").insertAfter(".top-rated-prod-position"); }) – VeggieBot May 23 '18 at 12:15
  • Sorry i should of posted the whole snippet but jquery doesnt run on wordpress at all without being wrapped in the ready statement. So i assumed it was a given. Anyways. Any idea why my script only works some of the time? If its not what i assumed above? – VeggieBot May 23 '18 at 12:16
  • SO what im saying is my code already has what you said i should do and yet the script only works some of the time. – VeggieBot May 23 '18 at 12:21
  • One thing I noticed that may be nit-picky. Your selectors are using classes i.e $(“.class”) and not ids $(“#id”). Is it possible you have more than one element with the “.top-rated-prod-position” or “.promoted-products-box” classes? – Jose Rojas May 23 '18 at 12:22
  • Thanks! And no, im sure these classes are unique and only used once per page. – VeggieBot May 23 '18 at 12:23
  • Before anything I would give those elements unique ids and change the selectors to use ids to see if that fixes the problem – Jose Rojas May 23 '18 at 12:24
  • Also is there any error being displayed in your browser’s developer tools -> console? – Jose Rojas May 23 '18 at 12:26
  • Yeah I agree however since im working in wordpress I dont wana overwrite a plugin file just to add an ID. Thats my only issue – VeggieBot May 23 '18 at 12:27
  • Nope no errors in console. Ill keep playing with it – VeggieBot May 23 '18 at 12:28
  • Found this. Your question may be answered already. https://stackoverflow.com/questions/1327085/jquery-ready-function-doesnt-work-in-wordpress – Jose Rojas May 23 '18 at 12:35