What is the best way to create exclusive toggle buttons using jQuery?

I am currently working on a project where I need to create functionality for three buttons, each triggering a unique graph effect. The key requirement is that when one button is pressed, the other two should be deactivated along with their corresponding functions.

Button 1 should activate Function 1 and deactivate Functions 2 and 3. Button 2 should activate Function 2 and deactivate Functions 1 and 3. Button 3 should activate Function 3 and deactivate Functions 1 and 2.

For example, pressing Button 1 will display a graph with points 14, 10, and 11. Button 2 will display points 26, 31, and 28, while Button 3 will display points 52, 48, and 38.

For reference, you can view the implementation on jsfiddle http://jsfiddle.net/sctcmr1h/6/

HTML

  <button type="button" class="btn" id="button1" >Button 1</button>
  <button type="button" class="btn" id="button2">Button 2</button>
  <button type="button" class="btn" id="button3">Button 3</button>

  <div id="container"></div>

CSS

.btn.active, .btn:active {
    background: #124364;
    text-decoration: none;
}
#container{
  width: 400px;
  height: 100%;
  background-color: #336699;
  color: white;
}

JavaScript

$(function button1() {
  var data = [{
    X: 14
  }, {
    X: 10
  }, {
    X: 11
  }];

  var processedData = [];
  Highcharts.each(data, function button1(d) {
    processedData.push(d.X);
  });

  // Create the chart
  $('#container').highcharts('StockChart', {
    rangeSelector: {
      selected: 1
    },

    series: [{
      data: processedData,
    }],

  });
});

$(function button2() {
  var data = [{
    X: 26
  }, {
    X: 31
  }, {
    X: 28
  }];

  var processedData = [];
  Highcharts.each(data, function button2(d) {
    processedData.push(d.X);
  });

  // Create the chart
  $('#container').highcharts('StockChart', {
    rangeSelector: {
      selected: 1
    },

    series: [{
      data: processedData,
    }],

  });
});

$(function button3() {
  var data = [{
    X: 52
  }, {
    X: 48
  }, {
    X: 38
  }];

  var processedData = [];
  Highcharts.each(data, function button3(d) {
    processedData.push(d.X);
  });

  // Create the chart
  $('#container').highcharts('StockChart', {
    rangeSelector: {
      selected: 1
    },

    series: [{
      data: processedData,
    }],

  });
});

http://jsfiddle.net/sctcmr1h/6/

My approach to tackling this problem involves utilizing specific JavaScript functions for the buttons to ensure exclusivity and proper functionality. Here is a simplified version of what I am attempting:

$(document).ready(function() {
$('#Button ID').click(function 1 2 or 3() {
if ($(this).hasClass('active')) {

  $('#container').hide();
} else {
  $('#container').show();
  function 1 2 or 3();
}
$(this).toggleClass('active');

});

Answer №1

I currently do not utilize highcharts, however, I can demonstrate how I would proceed with the remaining tasks:

var data = [
    [{ X: 14 }, { X: 10 }, { X: 11 }],
    [{ X: 26 }, { X: 31 }, { X: 28 }],
    [{ X: 52 }, { X: 48 }, { X: 38 }],
  ],
  displayChart = function(i){
    var processedData = data[i].map(function(point){
       return point.X;
    });
    $('#container').highcharts('StockChart', {
      rangeSelector: {
        selected: 1
      },
      series: [{
        data: processedData,
      }],
    });
  };
$('.btn-chart').click(function() {
  $('.btn').not(this).removeClass('active');
  $(this).toggleClass('active');
  displayChart($(this).attr('data-chart'));
});

Check out this jsfiddle link for a preview:

http://jsfiddle.net/mckinleymedia/sctcmr1h/7/

I omitted the hiding and showing of "#container" as it wasn't specified.

Moreover, I replaced the ids in the buttons with a "data-chart" attribute and a more specific class:

  <button type="button" class="btn btn-chart" data-chart="0">Details</button>
  <button type="button" class="btn btn-chart" data-chart="1">Details</button>
  <button type="button" class="btn btn-chart" data-chart="2">Details</button>

  <div id="container"></div>

I trust this information proves beneficial to you.

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

Issue with multiple dropdowns not functioning in Bootstrap 5

Before you criticize my imports, here are the scripts I am using: <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script ...

Prevent form submission once all tasks have been finalized

Hey there, I've been racking my brain for hours trying to solve this issue... I'm looking to disable my form after it's been submitted to prevent multiple submissions. However, every method I try seems to disable the button but also interfe ...

Leverage the power of personalized SCSS styles in combination with Bootstrap-Vue, Webpack, and

I have been working on an application using VueJS with Bootstrap-Vue and I encountered a challenge while trying to import a SCSS file to customize the Bootstrap variables and add some custom styles. Here are the steps I have taken so far: Installed node ...

Encountered issue while initializing object from controller in AngularJS

Here is the demonstration on how the fiddle appears: var app = angular.module('testApp', []); app.controller = angular.('testAppCtrl', function ($scope) { $scope.vehicle = { type: 'car', color: 're ...

How to Retrieve the Current div's ID in VueJS

When using the v-for directive to dynamically generate an id for my div, I need to pass this unique id to a specific function. <div v-for="(item, index) in items" :key="index" :id="'form' + index" > ...

Preserving form POST information between form handler and header invocation

I've hit a roadblock with this issue and could use some assistance. Thank you in advance for any help. I have a form on a page (guest/build.php) that contains several radio buttons: <form action="../php/build.php" method="POST"> <table class ...

LinkedIn's website consistently displays a "1 min read" indicator when sharing articles or

I am currently attempting to remove the '1 min read' text from the description when sharing content on LinkedIn. Example of '1 min read' Although I have added open graph tags to the page and confirmed that they do not contain '1 ...

Stopping the loop: Disabling the SetInterval function with ResponsiveVoice code in JavaScript

Currently, I am developing a queuing system and implementing voice announcements using Responsive Voice. I have used setInterval, but the issue is that the voice keeps looping without stopping. $( document ).ready(function() { setInterval(function() ...

Utilizing the "each" function in jQuery to create click events for buttons that are linked to specific paragraphs

Right now, I am facing a situation where I have three buttons, each assigned with an ID that matches their order. Upon clicking a button, the paragraph associated with that order should hide itself using .hide(). My challenge lies in finding out how to ut ...

"Toggling the parent element through jQuery within a search function

I have a similar structure in my table: <input id="mySearch" placeholder="Search..." type="text"/> <table> <th>Main header</th> <tbody id="searchable"> <tr class="parent"><td>Parent</td></tr> ...

Can we include an option to display all pages in one row on a single page?

Is it possible to include an option to display all rows alongside the current options of 10, 15, and 100? I've been unable to locate this feature in the documentation: Check out the Codesandbox example: https://codesandbox.io/s/muidatatables-custom-t ...

Using jQuery to initialize a slider with data obtained from a JSON request, which is retrieved from a PHP script

Currently, I am facing a challenge where I need to set up a jQuery Slider using data obtained from a PHP-SQL query that has been encoded into JSON format. The PHP side is functioning properly, but I am encountering difficulties in parsing the value (as th ...

Guide on converting a material datepicker date value into the format "MM-DD-YYYY" in Angular 6

I need help formatting the date below to MM-DD-YYYY format in my Angular 6 project. I've checked out various solutions on SO and other websites, but so far, none have worked for me. Currently, I am using Material's Angular DatePicker component. ...

Is it possible to create an animation with CSS3 transitions?

Experience a dynamic blinking border animation when hovering over the title: #link_list a:hover { border-left: 10px solid #E3E3E3; animation: blink 1s infinite; -webkit-animation: blink 1s infinite; -moz-animation: blink 1s infinite; -o-animation: blink 1 ...

"Discover the steps to seamlessly integrating Snappuzzle with jQuery on your

I am a beginner when it comes to javascript and jquery, and I recently came across the snappuzzle plugin which caught my interest. After visiting snappuzzle plugin, I decided to download and link jQuery, jQuery UI, and the snappuzle.js in my HTML file. I a ...

Having trouble with your jQuery learning and not seeing any results?

I have been attempting to utilize jQuery for a project, but unfortunately, nothing seems to be happening when I click the button. Despite my various attempts to modify the code, the desired effect still eludes me. I am specifically using Firefox as my bro ...

What methods can be used in VueJS to restrict users from entering numeric values?

I am struggling to create a validation that prevents users from inputting numeric values into a textbox. I have tried using a native JavaScript solution, but it does not seem to be working on my end. In my textbox, I have set up this trigger v-on:keyup=" ...

A method for increasing a counter using only an instance of a class or function without accessing its methods or properties in Javascript

Looking at the task ahead, let increment = new Increment(); I have been tasked with creating a Javascript class or function called Increment in order to achieve the following: console.log(`${increment}`) // should output 1 console.log(`${increment}`); ...

Create fluidly changing pictures within varying div elements

Hello there! I have a form consisting of four divs, each representing a full page to be printed like the one shown here: https://i.sstatic.net/w7N6E.png I've successfully created all the controls using AJAX without any issues. Then, I load the image ...

Surprisingly stumbled into the 'restricted' directory while switching the current directory to a temporary folder

I've encountered a strange issue while attempting to create and switch the working directory to a temporary folder using Node.js. Check out the code snippet below: var path = require('path') var fse = require('fs-extra') var TEST ...