Having trouble getting jQuery JavaScript to work on Wordpress and feeling lost about how to implement no-conflict mode syntax

Trying to implement the code from this Codepen http://codepen.io/eternalminerals/pen/qdGvMo on my WordPress website at

I understand that since WordPress is in no-conflict mode, I need to change $ to jQuery. I have made this adjustment and ensured that the script is in the header using a JS adder plugin called css-javascript-toolbox. However, the functionality is still not working as expected compared to the Codepen. I tested the Codepen without JavaScript and it behaves similarly to the WordPress page, indicating that the issue lies within the JavaScript code.

<script type='text/javascript'>
StarWars = (function() {

  /* 
   * Constructor
   */
  function StarWars(args) {
    // Context wrapper
    this.el = jQuery(args.el);

    // Audio for opening crawl
    this.audio = this.el.find('audio').get(0);

    // Initiate animation
    this.start = this.el.find('.start');

    // Animation container
    this.animation = this.el.find('.animation');

    // Reset animation and display start screen
    this.reset();

    // Start animation on click
    this.start.bind('click', jQuery.proxy(function() {
      this.start.hide();
      this.audio.play();
      this.el.append(this.animation);
    }, this));

    // Reset animation and show start screen
    jQuery(this.audio).bind('ended', jQuery.proxy(function() {
      this.audio.currentTime = 0;
      this.reset();
    }, this));
  }

  /*
   * Resets the animation and shows the start screen.
   */
  StarWars.prototype.reset = function() {
    this.start.show();
    this.cloned = this.animation.clone(true);
    this.animation.remove();
    this.animation = this.cloned;
  };

  return StarWars;
})();

new StarWars({
  el : '.starwars'
});
</script>

No javascript console errors are displayed on my website page, but it seems like there is no JavaScript controlling the HTML elements like in the Codepen. Any assistance on resolving this issue would be highly appreciated. Thank you!

Answer №1

To efficiently update your jQuery call and pass jQuery as its own function, you can follow the example below:

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

   // $ Works! You can test it with next line if you like
   // console.log($);

});

In addition, you can also pass jQuery in as the dollar sign, as demonstrated in the following code snippet. Note that any jQuery code using "$.apis()" instead of "jQuery.apis()" must be contained within this code block, which can also be loaded externally if needed.

(function($) {

    // $ Works! You can test it with next line if you like
    // console.log($);

})( jQuery );

For more detailed examples, you can visit: ()

This solution is specifically tailored for WordPress, but I have used it in a CMS platform where JS files are rendered on the backend before being sent out to the view. If you encounter a similar scenario where the dollar sign declaration causes issues, this approach should provide a workaround. Happy coding!

Answer №2

After researching on Wordpress embedded javascript on page doesn't work, I discovered that the simple solution was to wrap the script in a jQuery ready function:

jQuery(function() {
  /* your code here */
)};

The website is now functioning perfectly!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Azure SpeechSynthesizer encountered an error due to using HTTP instead of the expected HTTPS protocol. This issue can be resolved by installing the NPM package `microsoft

Recently, I have been encountering an issue with the microsoft-congnitiveservices-speech-sdk npm package. Everything was working smoothly until randomly an error started popping up. This could be due to a browser update or a minor package update - I'm ...

Adjust the dimensions of a nested element within a container that has padding applied

After browsing through numerous similar questions regarding this issue, I have not been able to find a solution that works for my specific case. The HTML code in question is as follows: a{ display: block; padding: 3px 20px; clear: both; font-weight: ...

What is the method for creating a rectangle with text inside using HTML and CSS?

Hello, I need help with achieving this design using HTML and CSS. Can you assist me, please? https://i.stack.imgur.com/xOHVX.jpg This is what I have attempted so far: Below is my CSS code: .line-lg{ width:120%; text-align: center; border-bot ...

Guide on how to send files to an API using a form in React with MUI

I am struggling with sending an image through the front-end to my back-end application that is set up to accept data. Here is the code I have: import { useState } from 'react'; import axios from '../../config'; import { useNavigate } fr ...

The position of the parent element's bounding box in relation to the child element

I've been mulling over this question for quite some time now, and I finally decided to bring it up. Hopefully, it's straightforward and not something that has been addressed before... Here's the scenario: I have a list of items with anchor ...

Extract core object from array of objects with lodash or javascript

In my code, I have an array of objects that each contain a base object with a set of values. My goal is to remove the base object from all the data and achieve the Expected result shown below. Here is an example of the array: [ { "100": { ...

The variable that contains a function is invoked, but the result is undefined

I'm having trouble with a function that should return John temp (2021) when called, but instead it's returning John undefined (undefined) const user = { username : 'John', type: 'temp', yearJoin: 2021, user ...

Combining Angular subscriptions to fetch multiple data streams

I am looking to retrieve the most recent subscription from a group of subscriptions. Whenever the value of my FormControl changes, I want to capture only the latest value after the user has finished typing. Below is the code snippet I am using - let cont ...

Searching for repeated values across disparate object fields?

Inquiring about the method to utilize mongoose for identifying duplicate values across different fields. Providing a sample document for reference: { "followers": { { "_id": "5bf6d610d3a3f31a6c75a9f4" }, ...

Interactive Component overlying Layer - HTML/CSS

Currently, I am working on a web application that features a navigation bar at the bottom of the screen. To enhance visibility, I decided to apply a linear gradient overlay above the underlying elements. This screenshot illustrates what I mean. However, I ...

Conceal the Angular Material toolbar (top navigation bar) automatically when scrolling downwards

In my Angular application, the main navigation consists of a standard toolbar positioned at the top of the page. My goal is to have this navigation bar smoothly scroll up with the user as they scroll down, and then reappear when they scroll back up. I at ...

@vx/enhanced responsiveness with TypeScript

I am currently utilizing the @vx/responsive library in an attempt to retrieve the width of a parent component. Below are snippets from my code: import * as React from 'react' import { inject, observer } from 'mobx-react' import { IGlob ...

Vuejs - Expanding Panels

Trying to implement an accordion using Vue.js has been a bit challenging for me. While I came across some examples online, my requirements are slightly different. In order to maintain SEO compatibility, I need to use "is" and "inline-template", which make ...

Intentionally introduce discrepancies in the errors during validation of an object using hapi/joi

const validationSchema = Joi.object().keys({ Id: Joi.number().required(), CustomerName: Joi.string() .trim() .required() .when('$isInValidCustomer', { i ...

Passing an undefined value to the database via AJAX upon clicking a button

Hi there, I'm currently working on a table where I'm trying to perform an inline edit and update the value in the database by clicking on a button (an image). I've attempted to use an onclick function, but it seems to show "value=undefined&a ...

Sending various FormData instances to Node Express

I am facing a challenge where I need to submit three forms with just one click. The data collected from these forms should then create three separate rows in the database through an API, triggering a POST request. How can I effectively pass all this data ( ...

Bar Chart Data Label Problem with HighCharts

My goal is to have the label positioned outside the bar stack. I attempted to achieve this using the code below, but it seems to be inconsistent in its results. dataLabels: { enabled: true, color: '#333', ...

Facebook news feeds displaying only the most recent 20 posts

I have my feeds stored in JSON format at this URL, but I am only able to see the last 20 posts. How can I retrieve all of my posts using JSON format? ...

Neglecting asynchronous Ajax functions once they have been called

I currently have a function that looks like this: $("#transfer").click(function(){ var token_rec = $("#token_rec").val(); var user_rec = $("#user_rec").val(); var subdomain_rec = $("#subdominio_rec").val(); var req_rec ...

When I navigate to the URL using a router-link, the v-for in my Vue.js component renders properly. However, if I manually type the URL or refresh the page, the v-for fails to render

Whenever I navigate to a specific URL that showcases icons of characters from a game, everything functions as expected and the icons are displayed. However, upon refreshing the page, the icons vanish. If I manually enter www.example.com/champions, the ico ...