Using the jQuery plugin multiple times within one website

I have a decent understanding of jQuery and I'm in the process of developing a plugin. Specifically, it's a dropdown element that I'm working on.

Everything functions correctly when there's only one dropdown on the site. However, when there are multiple dropdown elements, the plugin fails to work.

This is the code snippet that activates the plugin:

$('#OfficeUI .dropdown').each(function(index, item) {
    $(item).OfficeUIDropdown();
});

Below is the complete source code of the plugin:

$.fn.OfficeUIDropdown = function() {
    var dropdownElement = $(this); 
    $.fn.selectedItem = ''; 

    $(dropdownElement).addClass('no-select'); 
    $(dropdownElement).append('<i class="fa fa-sort-desc"></i>'); 
    $.fn.hasFocus = function() { return dropdownElement.hasClass('focus'); };

    // Other plugin functions...

    return this;
}

It's a lot of code, but I'm hopeful that someone can assist me. I'm open to any suggestions on how to enhance this plugin.

Here's a JsFiddle link to showcase the issue.

Clicking on the first dropdown's 'A' causes the second dropdown to open, which is puzzling to me.

Answer №1

Due to the way dropdownElement is defined within the plugin, the definition changes when calling other functions. To fix this, ensure that your function declarations are bound to a specific scope, this.

$.fn.hasFocus = function() { return this.hasClass('focus'); };
$.fn.isActive = function() { return this.hasClass('active'); };
$.fn.isMenuOpened = function() { return this.hasClass('opened'); };
$.fn.ToggleOpen = function() {
    // Determine if the menu is open or closed, then hide or show it accordingly.
    if (this.isMenuOpened()) {
        $('.elements', this).hide();
        this.removeClass('opened');
    } else {
        $('.elements', this).show();
        this.addClass('opened');
    }
}

View it in action on JSFiddle.

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

Focus on styling a single theader element within a jQuery Data Table with CSS

Struggling to work with a dynamic Jquery Data Table that has 10 table headers. I am having difficulty adding a class or an Id in the code to the specific th element with the title 'Unused'. In my .css file, I attempted: [title~= Unused] { ba ...

Develop an AJAX script for processing multiple form inputs in PHP and HTML

I am working on a code that involves multiple form submissions, but the submit functionality is not working due to having multiple submits on one page. I have realized that I need an Ajax script to handle this, but I am new to it. Can someone provide me wi ...

Display a D3 Collapsible Tree visualization using information stored in a variable

I am currently working on an app that requires the display of a collapsible tree graph using D3. The data needed for this graph is not stored in a file, but rather within the database. It is retrieved through an Ajax call to a rest service and then passed ...

Pagination Component for React Material-UI Table

I am interested in learning about Table Pagination in React UI Material. Currently, my goal is to retrieve and display data from an API in a Material UI Table. While I have successfully implemented some data from the API into the Material UI Table, I am ...

Designing a customizable header/banner for user personalization

Is it possible to create a custom feature header generator that allows users to personalize it with colors, images, and text, then save and add it to their website? Check out the feature banner demo I created to get an idea of what I'm aiming for. (T ...

odd appearance when objects make contact with one another

I am encountering a peculiar issue with my threejs objects in a scene. Whenever they get near each other or touch, I notice strange triangular artifacts forming at the borders of the objects, as shown in the image below. The renderer being used is THREE.W ...

Troubleshooting the malfunctioning Ajax Post in Asp.net Core with .Net 6 Action method

I have a question regarding an ajax call I'm making in my cshtml file. Here is the code snippet: $(document).ready(function(){ $('.dl-dir-list').click(function(e){ console.log($(e.target).data('path')); console. ...

Expanding file input fields in Javascript

I am facing an issue with my form and file input. I need to select images from a different folder. echo '<pre>'; var_dump($_FILES); echo '</pre>'; Upon submitting the form, only the last selected image is displayed, but I ...

Accessing data with Ajax using functions outside of the Ajax function

Is there a way to access variable data from an external source in my code? Any assistance would be greatly appreciated. ...

Enhancing the appearance of my website's shared content on Facebook: A guide

When I share links from well-known news sites like TNW and Engadget, the preview looks great with a thumbnail, bold title, and summary. But when I try to share one of my website's articles, it doesn't look as appealing. Is there a way to customiz ...

What is the appropriate command for "building" a fresh NPM project?

I'm currently working on a JS website with Three.js. I kicked off my project like this: $ npm init $ npm install three Can anyone guide me on where to place my code utilizing Three.js, and which npm command should I use to "compile" my script for dep ...

What methods can I employ in Javascript to automatically display search results obtained from multiple HTTP search queries?

In my tampermonkey script, I am attempting to process an array of names by performing a search and printing the page for each one. The script runs automatically upon loading the page, hence the necessity of the if statement. $(document).ready(function(){ ...

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

Retrieve just a fragment of the feedback by utilizing the .load directive

Hello there, I've been using Wordpress and I have a shortcode with a bunch of code to arrange my blogs in a specific layout. In addition, I've integrated the isotope plugin as well as the infinite scroll plugin. The infinite scroll feature utili ...

Implementing Voting Functionality with Ajax Submission

Can anyone help me with getting ajax functionality to work properly for my Acts_As_Votable buttons? Here's the current code I have: post_controller.rb def favorite @post = Post.find(params[:id]) @post.upvote_from current_user respond_to do |f ...

Using Javascript and jQuery, populate a dropdown menu with options that are extracted from a different dropdown menu

These are my two <select> elements: <select class="js-select-1"> <option disabled>Starting point</option> <option>A</option> <option>B</option> <option>C</option> <option>D</op ...

The vertical scrollbar appears to be malfunctioning

I'm experiencing an issue where the scrollbar is visible but not functioning as expected. I am utilizing CSS for styling the scrollbar and other layouts, along with HTML to apply the styling. #sub_menu, #content{ display: inline-block; } #sub_ ...

Symfony2 does not receive any feedback from the Ajax request

Perform an ajax POST request with no response: Here is the ajax request code snippet: $.ajax({ method: 'POST', url: "{{ path('app-like-add') }}", data: { imageId: id }, success: function(response) { ...

Issue encountered when integrating AJAX with PHP and HTML5 form

I've been working on solving a puzzle involving a contact form that uses AJAX and PHP. I decided to try reverse engineering the PHP code from this page (). However, when testing it out, the message gets stuck at "sending message...." after clicking "S ...

What is the best way to align HTML elements in a single row?

I have the following code snippet... <div class="header"> <div class="mainh"> <div class="table"> <ul> <li><a>smth</a></li> ...