Is there a way to make my DIVS update their content dynamically like buttons do, without manually adding an onclick function in the HTML code?

I am currently customizing a WordPress theme that lacks the option for onclick events on div elements. However, I can assign classes and IDs to them.

In my design, I have four spans in a row, and when each span is clicked, I intend for the corresponding paragraph to be displayed.

While I managed to achieve this functionality with buttons that have onclick attributes, I'm facing difficulties implementing it for columns.

I would appreciate assistance in reviewing the code and figuring out how to use JavaScript to change paragraphs by calling an ID without explicitly using onclick in the HTML. The onclick behavior could be defined in either JavaScript or CSS.

function changeElement(num) {
  document.getElementById(`paragraph_${num}`).style.display = 'block';
  const arr = [1, 2, 3, 4].filter((elem) => elem !== num);
  arr.forEach((elem) => {
    document.getElementById(`paragraph_${elem}`).style.display = 'none';
  })
}
body {
  width: 100%;
}

.none {
  display: none;
}

div {
  display: flex;
  flex-direction: row;
  gap: 20px;
  justify-items: center;
}

span {
  height: 50px;
  width: 50px;
  background-color: green;
}
// the divs that correspond to each button below
<div>
  <span>Div 1</span>
  <span>Div 2</span>
  <span>Div 3</span>
  <span>Div 4</span>
</div>
   
<p id="paragraph_1">paragraph 1</p>
<p id="paragraph_2" class="none">paragraph 2</p>
<p id="paragraph_3" class="none">paragraph 3</p>
<p id="paragraph_4" class="none">paragraph 4</p>
</body>

Answer №1

When it comes to not being able to add an 'onclick' attribute in the HTML, one solution is to trigger the JavaScript function by injecting it dynamically using the setAttribute() method.

Check out the code snippet below:

  function setEvent(){
    const Div1 = document.getElementById('div1');
    const Div2 = document.getElementById('div2');
    const Div3 = document.getElementById('div3');
    const Div4 = document.getElementById('div4');
    Div1.setAttribute("onclick", "changeElement(1)");
    Div2.setAttribute("onclick", 'changeElement(2)');
    Div3.setAttribute("onclick", 'changeElement(3)');
    Div4.setAttribute("onclick", 'changeElement(4)');
  }
  window.onload = setEvent();

  function changeElement(num) {
    document.getElementById(`paragraph_${num}`).style.display = 'block';
    const filterArr = [1, 2, 3, 4].filter((element) => element !== num);
    filterArr.forEach((element) => {
      document.getElementById(`paragraph_${element}`).style.display = 'none';
    })
  }
    body {
      width: 100%;
    }

    .none {
      display: none;
    }

    div {
      display: flex;
      flex-direction: row;
      gap: 20px;
      justify-items: center;
    }

    span {
      height: 50px;
      width: 50px;
      background-color: green;
    }
// the divs that correspond to each button below
<div>
  <span id='div1'>Div 1</span>
  <span id='div2'>Div 2</span>
  <span id='div3'>Div 3</span>
  <span id='div4'>Div 4</span>
</div>

<p id="paragraph_1">paragraph 1</p>
<p id="paragraph_2" class="none">paragraph 2</p>
<p id="paragraph_3" class="none">paragraph 3</p>
<p id="paragraph_4" class="none">paragraph 4</p>

<script>

</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

Retrieve the script's location from the server prior to the initialization of Angular

Is there a way to dynamically add a script in the index.html page based on the application version? I have a controller that retrieves the app version and attempted to achieve this using AngularJS: var resourceLoader = angular.module('MyTabs&apo ...

Is there a way to maintain the original indexing of a list after users have selected a filtered item in React using Webpack?

After implementing a filter (filteredCat) for my catalogue, the visual display works as expected. One issue I am facing is that even though the items are filtered, the logged index does not correspond to the new filtered list but instead reflects the inde ...

The declaration file for the module 'bootstrap/dist/js/bootstrap' could not be located

Currently, I am developing a Next.js application and have integrated Bootstrap for styling. However, I am encountering an error when trying to import the bootstrap.bundle.js file. I am facing the following error message: Could not find a declaration file f ...

Displaying MongoIds in HTML output for the user

Currently, I am in the process of developing a web application that utilizes MongoDB as its database management system. One challenge I am facing is finding a way to accurately identify which object the user has selected from a list on the screen, and the ...

When using Angular with mdbootstrap, the mdb-tabs directive will move to the end if the ngIf condition is true

Currently facing a challenge with a significant amount of code here. It is referenced as follows: "ng-uikit-pro-standard": "file:ng-uikit-pro-standard-8.3.0.tgz", I am attempting to display a tab between 1 and 3 if a certain condition ...

How can you retrieve the value of a CSS file in Javascript and CSS?

Imagine there is an element with the class .selector. This class defines its style. Once the page has finished loading, some JavaScript code is executed - the specifics are not important. What matters is that the CSS properties have set the object's ...

The width of Highcharts increases proportionally to the growth of the chart's width

I want to create a highcharts graph where the width increases as data points increase. Currently, I have: I am using vuejs with highcharts, but it should work similarly with jquery or other frameworks. <div class="col-md-6" style= ...

What is the process for building a JSON-formatted dictionary?

My intention is to structure my data in a way that can be accessed using a specific key. The current arrangement looks like this: const dict = []; dict.push({"student": "Brian", "id":"01", "grade":& ...

Troubles with HTML and div elements

I have a specific need to dynamically load HTML into a div container with the style attribute overflow set to hidden. I have implemented next and previous buttons for navigation, but I am facing an issue where the content overlaps at the beginning and end ...

Content within a scrollable div in IE7 only loads once the user starts scrolling

TL;DR: How can I make IE7 load all hidden elements within a scrollable div? I'm creating a collapsible menu for easy navigation through a series of pages. This menu has two states: collapsed and expanded. Think of the menu items as chapters in a b ...

Incorporating information collected from a modal form into a table using vue.js

insert code hereThis single page application allows users to input data into a modal, which is then automatically added to a table on the main page. var modal = document.getElementById('modalAdd'); var modalBtn = document.getElementById(' ...

Is it feasible to cancel or clear the queue for a jQuery fadeOut function after a delay is specified? If so,

Can anyone help me out with this question? Is there a way to eliminate the delay in chaining? Mn.Base.TopBox.show = function(timedur){ $('#element').fadeIn().delay(timedur).fadeOut(); } Mn.Base.TopBox.cancelFadeout = function(){ } I&apos ...

Toggle a MutationObserver using a button to stop and start monitoring for changes

Is there a way to connect a MutationObserver and disconnect it using the same button? I know how to do each separately, but I want to use just one button. How can I achieve this? Apologies for my poor English. var target = document.getElementsByClassNa ...

Execute the controller function with the value as a parameter

I encountered an issue while attempting to call a function in the c# controller and passing a value. The error message I received was: `'Unable to get property 'then' of undefined or null reference'. I also included the Driver Model but ...

Ways to retrieve the highest date value in an array

I'm running into an issue where I am trying to find the maximum day in an array of dates, but for some reason it keeps returning either Invalid Date or null. I'm not sure what's going wrong. Do you think I should convert the values to a diff ...

The send_keys() function in Selenium version 3.141.0 works perfectly on Windows, but unfortunately, it is not functioning correctly on Linux Debian 11

I've been experimenting with web automation using Selenium. Everything was running smoothly until I updated my packages - now the send_keys() method isn't functioning on Linux, but it's working fine on Windows with the same versions. I&apo ...

Step-by-step guide on populating a state using an array

I am having trouble populating a list within a state using the set method, as the state remains empty App.js // Initiates the secrets word game const startGame = () => { // pick word and pick category const { word, category } = pickWordAndCat ...

JavaScript code that loads a copied mesh object using three.js

Currently using three.js version r59, encountering difficulties when attempting to duplicate a loaded model. The goal is to create multiple models through looping, with the plan to apply textures at a later stage. for (var i=0; i<5-1; i++){ va ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

To ensure the smooth functioning of a React application running on a Docker container in Ubuntu 16.04, it is

I'm currently in the process of setting up a docker container for running a react app that sends a fetch request to another docker container containing a node server. The deployment is on Ubuntu 16.04, however, after building and deploying the contain ...