Communication among 3 buttons

This inquiry is a continuation of that discussion. Initially, the buttons on the page are not "linked" but become so when the user clicks on the blue button with an icon inside.

Here are the conditions:

  1. If two buttons are linked (action upon clicking the blue button), then the others should also link together (connecting with the numbers around) [this functionality is working]

  2. Afterwards, if the user clicks on any button, all three buttons should detach from the connected numbers

The following HTML code is being used (with Bootstrap 3):

<div class="col-sm-12 interfacesBridge">
    <h3 class="text-info">Interfaces</h3>

    <!-- Buttons Layout -->
</div>

In addition to the HTML, here is the jQuery code that complements it:

// JQuery Logic
(function($) {
   // Javascript Code Here....
})(jQuery);

I have made numerous attempts to achieve the desired result, but have hit a roadblock. Please refer to the accompanying jsfiddle demonstration.

Answer №1

Upon examination of the situation, the timing at which the click event is triggered is as follows:

  1. If something is bridged and there are more than 2 (including itself), then bridge all unbridged items.

  2. If something is unbridged and there are still more than 2 items bridged (indicating that all were previously bridged), unbridge all items.

Therefore, the logic can be modified to:

$('.linkInterfaces').click(function () {
    if ($(this).find('i').hasClass('fa-chain-broken')) {
        //targetFunc = setBridged;
        setBridged($(this));
        if ($('.interfacesBridge .bridged').length >= 2) {
            $('.linkInterfaces:not(.bridged)').trigger('click');
        }
    } else {
        unsetBridged($(this));           
        if ($('.interfacesBridge .bridged').length >= 2) {
            $('.interfacesBridge .bridged').trigger('click');
        }
    }
});

Modified jsfiddle.

In this scenario, it is also possible to extract the logic out, but keep in mind that if the conditions for bridging/unbridging change (e.g: from >= 2 to bridge to <= 1 to unbridge), separating the logic may be a better approach.

$('.linkInterfaces').click(function () {
    var relatedTargets;
    if ($(this).find('i').hasClass('fa-chain-broken')) {
        setBridged($(this));
        relatedTargets = '.linkInterfaces:not(.bridged)';
    } else {
        unsetBridged($(this));           
        relatedTargets = '.linkInterfaces.bridged';
    }

    // When there are more than 2 bridged elements upon clicking, we need to either link all or unlink all.
    if ($('.interfacesBridge .bridged').length >= 2) {
        $(relatedTargets).trigger('click');
    }
});

Additionally, note that the .trigger's second or later parameters will be passed to the event handler but will not trigger unless explicitly called within the event handler in your original code.

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

How to automatically redirect to new Django URL after Ajax function successfully runs?

I have implemented an AJAX function to check the validity of user input usernames. This function sends a request to a view which checks the validity and returns a JSON response. The AJAX function I have written makes a call to a specific URL with the user ...

What is the process for changing or finding the default icon for the Authentication Login in DNN?

Upon compilation, the code appears like this. How would you go about finding it? <div class="SteelBlue01_style"> <div class="SteelBlue01_top_bg"> <div id="c_head"> <div class="c_icon SteelBlue01_top_height> <img id="dnn ...

What purpose does the <noscript> tag serve in React?

Recently delving into the world of React, I've been working on a simple application by following this tutorial: https://reactjs.org/tutorial/tutorial.html. I've started modifying the code to suit my own project. While inspecting my HTML, I notic ...

Troubleshooting: Issues with Mod_rewrite affecting CSS, JS, and Image functionality

Today marks my first time posting a query in this forum. I'm currently facing an issue with mod_rewrite. Below is the structure of my filesystem: site_new/stylesheets/layout.css site_new/javascript/somescript.js site_new/hallendetails.php ...

Create a way to allow users to download html2canvas with a customized filename

I have a div where I want to use html2canvas to save a PNG file of its content. The issue is that the name of the saved file is static in my code and does not change unless I manually edit it. Is there a way to dynamically set the filename based on user i ...

Using jQuery to remove the last two characters from a specified class

I have a simple task at hand. I am trying to use the slice method in JavaScript to remove the last two characters from a string that is generated dynamically within a shopping cart. Instead of displaying a product as $28.00, I want it to display as $28. S ...

Controller fails to initialize when utilizing $location.path or $state.go

Issue with Controller Initialization after Redirect in Ionic App I have encountered an issue where the controller is not initializing on the same page when I use $state.go or $location.href. In my Ionic app, I am using a sidemenu to pass category Id to th ...

What is the correct way to format text as superscript?

In my application, I have noticed that there are a lot of numbers and letters displayed in superscript. For example, using <span style="vertical-align: super;">3</span> results in X<sup>3</sup>. However, simply using the sup tag als ...

Tips for setting the background image of the body once the image has finished loading

On my website, I have decided to incorporate high-resolution images as the background for the body. However, when I use document.body.style.backgroundImage = "url('URL OF PICTURE')";, the image loads vertically down the page which is not ideal. I ...

Angular processes the expression as though it were part of the HTML

I need help finding a feature in Angular that can achieve the following task: var data = { name: 'Jane Smith', age: 30 } someFunction('Hey there, {{name}}, you are {{age}} years old', data) // should give output 'Hey there ...

Null reference exception in Typescript + NextJS

I am facing an issue where the ref to a custom child component in my parent component is always null, preventing me from calling methods on it. Even though I believe I have implemented everything correctly, the ref (named CanvasUI) remains null and I can& ...

Error: [$injector:unpr] Oh no! The AuthServiceProvider Angular Service seems to be MIA

I am currently working on a small AngularJS project and encountering an issue with my service files not being successfully injected into the controllers. I have double-checked for any syntax errors, but despite trying different variations, the problem pers ...

Creating dynamic URL routes for a static website using Vue

I am facing a challenge with my static site as I am unable to add rewrites through htaccess. Currently, our site is built using Vue on top of static .html templates such as \example\index.html. When I want to create a subpage within this layout, ...

There is an issue with the functionality of OrbitControls and dat.gui text

Incorporating three.js and dat.gui, I am utilizing a text property within my project. Additionally, my scene features OrbitControls: cameraControl = new THREE.OrbitControls(camera); cameraControl.update(); A complication arises in this particular setup. ...

There is only one source that plays for the array number - no additional sources are involved

I'm currently working on adding a feature to my school project Wack-a-Mole game where clicking on Owen Wilson's face will play one of several audio files. I've tried using a plain array with the file names, but that didn't work. The cur ...

Implementing a Django application feature that enables Ajax auto-complete functionality after the user inputs at least 2 characters with a

Could anyone help me with modifying this code snippet in my Django app? I want to restrict the Ajax functionality to trigger only when there are at least 2 characters entered in the search input field. Also, is there a way to introduce a 1-second delay b ...

What is the best way to use jQuery to wrap two elements while maintaining the integrity of their parent

I'm currently facing an issue with wrapping two elements in jQuery. Occasionally, there may be an invisible duplicate of the parent element present. When this happens, the element from the hidden div also gets wrapped in the visible one: jQuery(d ...

Incorporating the latest version of SMINT into your Shopify store

Appreciate the help you're about to give. Here's the process of incorporating Smint v3.0 into Shopify: Added jquery.min.js and jquery.smint.js to asset files Inserted the following code within the tag of theme.liquid {{ 'jquery.mi ...

updating deeply nested structures in immutable JS

I encountered an 'invalid keypath' error while attempting to modify my structure: state = fromJS({ cmsData: { "pages": [ { "name": "page1", "content": { "header": "Example header", "intro": "Exampl ...

How about sending back the response instead of not returning it, in Node.js

I need help finishing a code block if the condition is met. If isBookmark is true, I want to continue with the following steps and log '1' to the console. checkLecture(addLectureInformation) .then(() => { return insertLectu ...