Using a click event to target the next div and apply a CSS class using Typescript

I am trying to create a Typescript function that will locate the next div and apply a CSS class to it. Here is what I have attempted:

<ul>
    <li><a href="#" onclick="toggle()">Item 1</a></li>
    <div class="content hide"></div>
    <li><a href="#" onclick="toggle()">Item 2</a></li>
    <div class="content hide"></div>
    <li><a href="#" onclick="toggle()">Item 3</a></li>
    <div class="content hide"></div>
    <li><a href="#" onclick="toggle()">Item 4</a></li>
    <div class="content hide"></div>
    <li><a href="#" onclick="toggle()">Item 5</a></li>
    <div class="content hide"></div>
</ul>

Here is my attempt at the Typescript function:

function toggle(){
   this.parent().next('.content').class('hide');
}

Any suggestions or feedback would be greatly appreciated.

Answer №1

this isn't what you assume! It's important to pass the current element as this as an argument.

Also, remember there is no method called .class, you should be using the .toggleClass method instead.

function toggle(elem) {
  $(elem).parent().next('.content').toggleClass('hide');
}
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
  <li><a href="#" onclick="toggle(this)">Item 1</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 2</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 3</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 4</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 5</a>
  </li>
  <div class="content hide">Content Goes here!</div>
</ul>

However, it's recommended to use jQuery-event-binding rather than Inline-event-binding

function toggle() {
  $(this).parent().next('.content').toggleClass('hide'); //this will refer to current element!
}
$('li a').on('click', toggle);
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js></script>
<ul>
  <li><a href="#">Item 1</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#" onclick="toggle(this)">Item 2</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#">Item 3</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#">Item 4</a>
  </li>
  <div class="content hide">Content Goes here!</div>
  <li><a href="#">Item 5</a>
  </li>
  <div class="content hide">Content Goes here!</div>
</ul>

Answer №2

Sample Code

<a (click)="toggleVisibility($event)" class="collapsible-header">Toggle visibility</a>
<div class="collapsible-body" style="display:none">
   <ul>
     <li>Node1</li>
     <li>Node2</li>
     <li>Node3</li>
   </ul>
</div>

JavaScript Function

toggleVisibility(elem){
    const target = elem
    const display = target.toElement.nextSibling.style.display

    if(display == 'block'){
      target.toElement.nextSibling.style.display = 'none'
    }else{
      target.toElement.nextSibling.style.display = 'block'
    }
  }

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

having difficulty transmitting parameter to angular directive

After assigning a collection to a source variable, I am trying to activate a third party control (bootstrap-select) using a directive that watches the assigned collection. angular .module('app').directive('bootstrapDropdown', ['$t ...

The pagination component in React with Material-ui functions properly on a local environment, but encounters issues when deployed

Looking for some assistance with a persistent issue I've run into. Can anyone lend a hand? [x] The problem persists in the latest release. [x] After checking the repository's issues, I'm confident this is not a duplicate. Current Behavior ...

Unlocking the treasures of JSON data in JavaScriptDiscovering the secrets of extracting JSON

let info = { "@type": "Movie", "url": "/title/tt0443272/", "name": "Lincoln", "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA ...

Menu with options labeled using IDs in FluentUI/react-northstar

I'm currently working on creating a dropdown menu using the FluentUI/react-northstar Dropdown component. The issue I'm facing is that the 'items' prop for this component only accepts a 'string[]' for the names to be displayed ...

What is the process to manually trigger hot reload in Flutter?

I am currently developing a Node.js application to make changes to Flutter code by inserting lines of code into it. My goal is to view these updates in real-time. Is there a way to implement hot reload so that every time I finish writing a line in the file ...

Is it necessary to manually validate parameters in TypeScript when developing a library?

Understanding the basic workings of TypeScript, it's clear that TypeScript transpiles code to JavaScript without adding extra behavior like type checking during execution. For instance, function example(parameter: string): void { console.log(paramet ...

Creating a code script for the purpose of automating npm commands

Currently, I am immersed in an angular js project and I have a desire to streamline the execution of the following two commands. ./node_modules/protractor/bin/webdriver-manager update ./node_modules/protractor/bin/webdriver-manager start The challenge li ...

Substitute a JSONP API call using $.ajax() with a direct server-to-server API call

My javascript application utilizes an ajax function that has the following structure: $.ajax({ url: apiURL, dataType: 'jsonp', success: function(data) { if (data.ok) { //perform actions }}}); Everything was working perfectly until I ...

Attempting to highlight a specific list item by using the CSS current class to emphasize its active state

I've been experimenting with different solutions I found in previous questions, but unfortunately, none of them have worked for me. I suspect the issue lies in the fact that the element is deeply nested within CSS classes, and my lack of experience is ...

How can I cancel or reset a timeInterval in AngularJS?

In my project demo, I have implemented a feature that fetches data from the server at regular intervals using $interval. Now, I am looking for a way to stop or cancel this process. Can you guide me on how to achieve this? And if I need to restart the proce ...

What is the best way to trigger an event in VueJS?

I recently implemented a table using Vuetify in my project. The table is now split into two components - the Table component and the Row component. My challenge is how to handle the same function, this.selected = !this.selected!, when dealing with 2 differ ...

Tips on slowing down the Jquery UIBlock Plugin

Currently, I am implementing a plugin found at http://jquery.malsup.com/block/#overview. However, I am interested in configuring the blockUI feature to only be displayed if an AJAX request takes longer than 1 second. Otherwise, I would prefer for nothing ...

I am having difficulty accessing specific data in JSON using Searchkit's RefinementListFilter

Utilizing searchkit for a website, I am encountering issues accessing previously converted data in json format. The structure of my json directory is as follows: (...) hits: 0: _index: content _type: content _source: ...

Tips for Looping through an Object within another Object

Is there a way to retrieve values from an Object that contains another Object nested inside? I am not overly concerned about the keys, but it would be helpful if I could access them as well. Here is an example of the response: res = {data: {name: 'na ...

In AngularJS, I've created a collection of checkboxes with a submit button ready to go

One of my goals is to make the cancel button available only when at least one job is selected. Below is my HTML View <table> <tr ng-repeat="x in jobs" ng-class-odd="'odd'" ng-class-even="'even'"> <td style="widt ...

Guide on retrieving data from an axios promise in JavaScript

I am struggling to manage the output of multiple lists retrieved through an axios API call made in JavaScript. I want to know how to effectively log the results and save them for future use, particularly for creating a data visualization. Here is my curre ...

HTML table row content should be aligned to the left side

I am attempting to align the data in the 'Address' column without any margin. I want it to start from the left since it's overflowing. You can find the HTML, CSS, and JS code here Even though I tried using <td align="left">..</td& ...

When calling an API endpoint, nodeJS is unable to access the local path

I've encountered a strange issue with my code. When I run it as a standalone file, everything works perfectly fine. However, when I try to utilize it in my API endpoint and make a request using Postman, it doesn't seem to function properly. What ...

Storing client-requested data locally

Is it possible to use JavaScript to make an AJAX request to fetch data from a server, then prompt the user to save this data on their computer for later access outside of the browser session? Can this saving functionality be achieved without using a Flas ...

Unable to fetch information from the controllerAPI function within the tsx file due to a Module Parse error

I am currently working on fetching records from a database using ControllerApi and displaying them through React. The code snippet below is from a file with a *.tsx extension: import React, { useState } from 'react'; import ReactDOM from 'r ...