The jQuery code functions properly on index.html but encounters issues when implemented on index.php or within wordpress theme files

As a beginner in coding, particularly in javascript and jQuery, I am seeking assistance with an issue. I am currently working on developing a WP theme, so all my code is within WP files. I have noticed that code that functions perfectly in an index.html file does not seem to work in my WP theme files, and I haven't been able to pinpoint the reason for this yet. Here's the latest example:

The front page of my theme is divided into three sections using divs. In the third section/div, I want to display different divs based on which button is clicked. Essentially, when Button 1 is clicked, it should show the content of div1 while hiding the others. Similarly, when Button 2 is clicked, the content of div2 should be visible while hiding the other divs. I require a total of four buttons/links and corresponding divs with unique content.

I came across a jQuery code on codepen that almost meets my requirements functionally. (Refer to code below or click here for the original code). When I copied and pasted this code into my html.index files, everything worked as expected just like on codepen. However, upon copying the same code into my WordPress theme files, the jQuery functionality ceased to work. I read that in WP, you cannot directly use $, so I replaced all instances with jQuery. Despite this modification, the code still doesn't run. Can anyone shed light on why this might be happening?

While inspecting this in Chrome, I encountered the following error displayed twice: "Failed to load resource: the server responded with a status of index.js:1 404 (Not Found)".

To verify if jQuery was loading correctly in my WP files, I tested it with a simple code snippet from w3schools and confirmed that it was indeed added to my WP theme without any issues.

Here is the code snippet:

HTML:

<a href="#" class="button">
    Button 1
</a>
<a href="#" class="button">
    Button 2
</a>
<a href="#" class="button">
    Button 3
</a>
<a href="#" class="button">
    Button 4
</a>

<div class="content">
  <div class="content-1 active">Jana 1 Content</div>
  <div class="content-2">Button 2 Content</div>
  <div class="content-2">Button 3 Content</div>
  <div class="content-2">Button 4 Content</div>
</div>

CSS:

a.button {
  display:inline-block;
  width:100px;
  height:50px;
  background-color:blue;
  color:#fff;
  line-height:50px;
  text-align:center;
  text-decoration: none;
}

a.active {
  background-color:red;
}

.content {
  margin-top:30px;
}

div[class*="content-"] { 
  display:none;
}

div.active { 
  display:block;
}

jQuery:


jQuery('.button').first().addClass('active');

jQuery('.button').click(function(){
  var jQuerythis = jQuery(this);
  jQuerysiblings = jQuerythis.parent().children(),
  position = jQuerysiblings.index(jQuerythis);
  console.log (position);

  jQuery('.content div').removeClass('active').eq(position).addClass('active');

  jQuerysiblings.removeClass('active');
  jQuerythis.addClass('active');
})

Integration in WP theme:

<?php

function lux_files() {
 wp_register_script( "index", plugins_url( "index.js", __FILE__), array( "jquery"));
 wp_enqueue_script ( "index");
 wp_enqueue_script( "javascript", get_template_directory_uri() . '/index.js', array(), false );
 wp_enqueue_style("font-awesome", "https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css");
 wp_enqueue_style("google-fonts", "//fonts.googleapis.com/css?family=Montserrat:400,700|Raleway:400,700&display=swap");
 wp_enqueue_style("main_styles", get_stylesheet_uri());
}

add_action('wp_enqueue_scripts', 'lux_files');



function lux_features() {
  add_theme_support('title-tag');
}

add_action('after_setup_theme', 'lux_features');

?>

Answer №1

Make sure the document is fully loaded before executing your jQuery script. Follow these steps:

$(function () { 

// Insert your jQuery code here 

}); 

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

Guide on leveraging event delegation to trigger a function depending on the id of the clicked element

Although I have experience with event delegation, I am currently facing a challenge in setting up a single event listener that can execute one of three functions based on the ID of the element clicked. Here is the existing code without event delegation: ...

Ways to incorporate External JS and CSS files into Angular 5 (loading files with a delay)

I have encountered some challenges while attempting to import external JS and CSS files into my Angular 5 application. Below is the code snippet that I have tried so far: Component.ts : ngOnInit() { this.loadScript(); // also attempted with ...

Perform an ajax POST call to a server using ajax/jQuery techniques

I am attempting to utilize ajax to send a post request to a different domain and receive a json response. The server is located within my company premises and the logs show that it is indeed sending back a json response. Below are two samples of my attemp ...

Instead of displaying a regular text box, the output unexpectedly shows "Printing [object HTML

There are some HTML and JavaScript files that I have. I've written some functions in my JavaScript file to save the values of different input fields. However, when I try to print the description, it just displays [object HTMLInputElement]. This mak ...

Unable to showcase information in the center of an HTML document

Hello, I'm facing an issue with my HTML page that has a left vertical nav-bar. Despite my efforts, I can't seem to display content (text) in the center of the page as shown in the screenshot with the red oval. I've attempted inserting text ...

Troubleshooting the unresponsive nature of the multi-level menu

I have incorporated a specific plugin into my application Check out my application here To access the menu, click on the third green button followed by any yellow button on the right side. However, the menu appears underneath another div rendering it unc ...

What is the best way to place this dropdown in a fixed position within a parent element with overflow scrolling

I am facing an issue with a dropdown menu inside a parent div. The parent div has a fixed height and is set to overflow: auto. My goal is to have the menu extend beyond the boundaries of the parent when opened, but currently it just increases the height of ...

Sorting dates in Datatables while deferring rendering

I have implemented deferRender to load data into my datatable, but I am facing a challenge with sorting on the client side rather than the server side. In the past, I utilized HTML5 data attributes (http://www.datatables.net/examples/advanced_init/html5-d ...

Using JavaScript to block form submission based on AJAX response

I am having trouble understanding why this code is not working as expected to prevent a submit. I have made sure all the HTML elements are properly linked and all alerts display correctly. It doesn't seem like I am losing scope on the event. If anyone ...

The WooCommerce welcome email contains a variety of header and footer designs for a unique and customizable design

When importing users using the wp_insert_user function, I am facing an issue with sending WooCommerce new account emails. If there is only one user being imported, everything works fine. However, when multiple users are imported, the email contains multipl ...

Leverage GZIP compression, JSON data format for responses, and JQuery

I am interested in optimizing my responses by compressing them with GZIP whenever possible. I experimented with the Compression filter code provided for free download on the headfirst site, and it worked effectively for html, images, css, and javascript. ...

Using JQuery to assign a class to every third item in a list

How can I add a class name to every third list item using addClass() instead of css()? I tried the following: $('ul li:nth-child(3n)').addClass('grey'); However, it doesn't seem to be working. What did I do wrong? Here is my co ...

Place a label within a container and surround it with a single border. Inside the container, create an unordered list

I'm attempting to design a filter dropdown feature where only the label of the dropdown is visible at first, and then upon clicking the label, a list of options will drop down over the top of the remaining content using absolute positioning. The chall ...

Troubleshooting the Issue of Table Append not Functioning in Live Environment

I'm currently in the process of developing a website using Bootstrap, and I'm facing an issue where one of the tables gets cleared out and updated with new data when a button is clicked. This functionality works perfectly fine during testing on V ...

The picture is unavailable for inline viewing

I am currently working with bootstrap and I have a requirement to show an image followed by some text. However, despite having enough space after the image, the text keeps getting pushed to the next line. Below is my code: <div class="splash"> < ...

Using multiple html files with ui-router's ui-view feature

Is it possible to create a complex UI using multiple HTML files with ui-view in AngularJS? I am trying to achieve a layout similar to this: I attempted to implement something on Plunker, but it seems like I'm struggling to grasp the underlying concep ...

Fading in and out occurs several times while scrolling through the window

My goal is to update the logo image source with a fadeIn and fadeOut effect when scrolling up or down. The issue I'm facing is that the effect happens multiple times even after just one scroll, resulting in the logo flashing many times before finally ...

How to change the divider color in Angular Material table's header row

Currently struggling with customizing the divider appearance in the Angular Material table. Despite trying various approaches in the Chrome dev tools, I am unable to modify the color and thickness of the divider after the header row. It seems that the bord ...

What methods can I use to create a navigation bar similar to this design?

Lately, I've noticed a growing trend in navigation bars that are designed to resemble waves. Wavey Navbar I'm eager to incorporate a similar navbar into my website, but I'm struggling to figure out how to do it. I'm working with react ...

How can I create a jQuery Listener for 2 different events simultaneously?

One issue I am facing is triggering a function when an event occurs in a table cell or when an item is selected from a dropdown menu. Currently, I have code that works for the table cell event: $('td[id^="tblcell"]').click(function() { ... ... d ...