Having trouble getting the Javascript dropdown script to work on a Wordpress page?

Hello all, I've been experimenting with creating a simple dropdown menu for my Wordpress website. The idea is that when a user clicks on a specific text, a dropdown menu with various links will appear. I followed the guidance from W3 Schools, but unfortunately, I haven't been able to make it work on my site as intended.

I attempted to add the code to functions.php, but it caused my site to crash. When I added it to header.php, the site functioned fine, but the code itself didn't work. I'm a bit stuck at this point and could really use some expertise.

I'm not well-versed in Javascript, so I'm struggling to pinpoint the root of the issue. Any advice or guidance would be highly appreciated.

Below is the code that I've been using:

JAVASCRIPT:

// MENU DROPDOWN DESPLEGABLE AL CLICKAR ENLACES
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
add_action ('wp_head', 'myFunction');

HTML:

<div class="dropdown">
  <p onclick="myFunction()" class="dropbtn">Dropdown</p>
  <div id="myDropdown" class="dropdown-content">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

CSS:

/* Dropdown Button */
/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
  background-color: #5e7c6d;
  cursor: url(https://imthemoisturizer.com/wp-content/uploads/2020/07/Cursor-2.png), auto;
}

/* The container <div> - needed to position the dropdown content */
.dropdown {
  position: relative;
  display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #ddd; cursor: url(https://imthemoisturizer.com/wp-content/uploads/2020/07/Cursor-2.png), auto;}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

Thank you in advance for any help, and I hope you all have a great day!

Answer №1

After attempting to insert the code into functions.php, my website abruptly crashed.

The reason for this mishap is that the code you tried to implement is Javascript, while functions.php is a PHP file. PHP interprets code differently from Javascript, so when the incompatible code was introduced, it caused the crash you encountered.

However, when the code was added to header.php, the site functioned properly.

This likely occurred because you either pasted the Javascript directly into the HTML, resulting in it being displayed as plain text, or placed it within a <script> tag where it should be. Although the latter method was more suitable, there may have been an issue with the code itself. To demonstrate, the snippet below functions correctly when the last line of the JS code is commented out:

//MENU DROPDOWN DESPLEGABLE AL CLICKAR ENLACES
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
  let myDropdown = document.getElementById("myDropdown");
  if (myDropdown) {
    document.getElementById("myDropdown").classList.toggle("show");
  }
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

//add_action ('wp_head', 'myFunction');
/* Dropdown Button */
/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
  background-color: #5e7c6d;
  cursor: url(https://imthemoisturizer.com/wp-content/uploads/2020/07/Cursor-2.png), auto;
}

/* The container <div> - needed to position the dropdown content */
.dropdown {
  position: relative;
  display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #ddd; cursor: url(https://imthemoisturizer.com/wp-content/uploads/2020/07/Cursor-2.png), auto;}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}
<div class="dropdown">
  <p onclick="myFunction()" class="dropbtn">Dropdown</p>
  <div id="myDropdown" class="dropdown-content">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

Essentially, if the above Javascript is loaded onto your page and the corresponding HTML renders in the page source, your desired functionality should work seamlessly. Consider creating a myfile.js file to contain your Javascript code, which can be then loaded into your site using a script tag like this:

<script src="path/to/myfile.js"></script>

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

Learn the process of invoking an Angular scope function from within a JavaScript function located within a controller

In my Angular controller, I have a JavaScript function where I am trying to call an Angular function. However, I am encountering the error: $scope.Name is not a function, $scope.dates is not a function. function validation() { $scope.page ...

How to deactivate or modify the href attribute of an anchor element using jQuery

My HTML code looks something like this: <div id="StoreLocatorPlaceHolder_ctl07_ctl00_ctl00_pager_ctl00_ctl00_numeric" class="sf_pagerNumeric"> <a href="http://www.domain.com/store-list">1</a> <a href="http://www.domain.com/sto ...

Unable to import necessary modules within my React TypeScript project

I am currently building a React/Express application with TypeScript. While I'm not very familiar with it, I've decided to use it to expand my knowledge. However, I've encountered an issue when trying to import one component into another comp ...

Encountering a sudden problem while running gulp build due to a node_module - Surprising occurrence of Unexpected

Encountering an unexpected issue while running a gulp build process for a web app that I am struggling to resolve. The problem did not exist on the evening of 25/01/2019, but when attempting to execute the gulp build process this morning (30/01/2019), an ...

The JSON.stringify function is returning inaccurate index structures

https://i.sstatic.net/ptMcW.png I am attempting to use the JSON.stringify() method on my object (refer to the screenshot). However, the result I am getting is not what I expected - the indexes of the objects are in the wrong order. You can view the comp ...

Employing an unchanging Map format for observation

I'm currently working on implementing a synchronization mechanism using observable and Map structures from Immutable.js. However, I'm encountering an issue where the Map is unable to function as an observable or perhaps I might be approaching it ...

What is the process for preloading a Ramda curried function with items from an Array?

In my project, I have a collection called tagsList that contains approximately 20 tags, and another array called termIds which holds up to 3 tag ids. My current task involves identifying tags in the tagsList that match the ids in termIds, and then applyin ...

What is the best way to add the current date and time using Javascript new Date() into MongoDB

Using Javascript: currentTime = new Date(); $.getJSON("/my_api",{ current_time: currentTime, format: 'json' }); With Python: var current_time = request.GET.current_time # creating an entry new_entry = {} # adding other key-value pairs ...

Leveraging Next.js for "client-side rendering" in React Encapsulations

My dilemma involves a component housing content crucial for SEO optimization. Here is an excerpt from my code: <AnimatedElement className="flex flex-col justify-start items-center gap-4 w-full" duration={500}> <h2 class ...

Update image source dynamically using AJAX and jQuery

Within my app, there exists a web page that contains numerous images with dynamically generated source URLs obtained by sending get requests to the rails server. Initially, these images are assigned a default source. Upon loading the page, another request ...

Vue function that inserts <br> tags for addresses

My Vue filter retrieves and combines address details with a , Vue.filter('address', (address, countryNames = []) => { const formattedAddress = [ address?.name, address?.company, address?.add1, address?.add2, address?.town ...

Tips for Disabling Alert Pop-ups when Launching Desktop Applications from a Browser

Is there a way to prevent the alert pop-up when launching a desktop application from a web browser? For instance, when typing calculator:// in the browser, we want to eliminate the alert box using an Angular TypeScript file. see image reference ...

Link the values of mongoose array to a distinct identifier

This question may come across as vague, but I'll do my best to explain it clearly. Just a heads up, I'm relatively new to working with mongoose :) So, I have this mongoose schema where different values are stored for each user: let userSchema = ...

Configuring Tailwind CSS with PostCSS in a Nuxt project

Error Message "In order to avoid issues with features like alias resolving inside your CSS, please make sure to use build.postcss in your nuxt.config.js file instead of an external configuration file. Support for external config files will be depreca ...

Unable to assign value to Ref data property in Vue3 due to undefined item

Recently, I've been utilizing Vue3 and Nuxt3 to work on a project. My main task involves extracting the :id parameter from the URL and checking if it matches an ID in a JSON file. If there is a match, I update a reference data point called 'exist ...

What steps do I need to take to integrate Twilio's SMS service into an HTML document?

I have been searching for solutions using php and node.js (which is a derivative of js, so it should work), but I came across this library: <script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.min.js"></script> ...

The Angular 2 service is not transmitting the POST data in the correct format, although it functions properly when transmitted through PostMan

When the POST data is transmitted from the Angular 2 service in this manner: const data = new FormData(); data.append('date', '12/01'); data.append('weight', '170'); return this.http.post(this.u ...

What is the best way to switch the visibility of a div on click from another div?

My goal is to make a div toggle visible or hidden when another div is clicked. The only connection between the two divs is that they are both nested within the same parent div. There's a DIV element with the class of "comment" which contains a DIV ele ...

Tips for creating a loading page that displays while your website loads in the background

Is there a way to display a loading animation or image while my website is loading in the background? I've noticed that it takes about a minute for my website to fully load. I attempted to use <meta http-equiv="refresh" content="1000 ...

Change the language of the website using JavaScript/JSON

Creating a website and aiming to utilize JavaScript for the following: If the browser language is set to French, retrieve the text from languageFr.json, otherwise, retrieve the text from languageEn.json. Here is a snippet of the code I have so far: JSON ...