Ways to display a different div when clicking on a div?

Good afternoon,

I've noticed that this question has been asked numerous times before, but none of the solutions provided seem to work for my specific issue.

My problem involves a div with the class .title3. I want another div with the class .Content3 to be displayed when the user clicks on it. However, it's not functioning as intended.

Below is a snippet of my HTML code where I encountered this problem:

<body style="background-color:#171717">

<div class="pseudo3">
     <div class="one3">
          <div class="Content3">
              <p class="close">X</p>
              <form action="order.php">
                <input type="text" value="First & Last Name">
                <input type="email" value="Your e-mail">
                <input type="text" value="Your phone number">
                <textarea>Write your feedback here</textarea>
                <button>Send</button>
              </form>
           </div>
           <div onmouseclick="showDiv()" class="title3">
                FEEDBACK
           </div>
      </div>
</div>


<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
  function showDiv() {
    var x = document.getElementsByClassName("title3");
      if (x.click === true) {
        document.getElementsByClassName("Content3").style.display = "block";
      }
  }
    </script>
</body>

CSS:

/* The Form Style */

form {
    width: 100%;
    height: 100%;
}

form input {
    width: 100%;
    height: 35px;
    color: #8b8b8b;
    font-family: 'Lato', sans-serif;
    background-color: #171717;
    padding: 12px;
    border: 0;
    outline: none;
    border-top: 0.15px solid #262323;
    border-left: 0.15px solid #262323;
    border-right: 0.15px solid #262323;
}

form textarea {
    min-width: 100%;
    max-width: 100%;
    min-height: 200px;
    max-height: 200px;
    color: #8b8b8b;
    font-family: 'Lato', sans-serif;
    background-color: #171717;
    padding: 12px;
    border: 0;
    outline: none;
    border-top: 0.15px solid #262323;
    border-left: 0.15px solid #262323;
    border-right: 0.15px solid #262323;
}

form button {
    width: 100%;
    height: 45px;
    position: relative;
    top: -3px;
    color: #8b8b8b;
    font-family: 'Lato', sans-serif;
    background-color: #171717;
    border: 0.15px solid #262323;
    outline: none;
    font-size: 20px;
}
input:focus,
textarea:focus,
button:focus{
    background-color: #212020;
    border-top: 0.15px solid #1f1616;
    border-left: 0.15px solid #1f1616;
    border-right: 0.15px solid #1f1616;
}

/* Content3 style */

.Content3 {
    width: 300px;
    height: 350px;
    position: absolute;
    z-index: 2;
    display:none;
}

/* one3 style */

.one3 {
    width: 300px;
    height: 350px;
    transition: 0.3s ease;
    position: relative;
    background-color: #141414;
}

/* pseudo3 style */

.pseudo3 {
    width: 320px;
    padding: 10px;
    border-top: 2px solid #b95e1c;
    border-bottom: 2px solid #ad7145;
    background-image:
        linear-gradient(#b95e1c, #ad7145),
        linear-gradient(#b95e1c, #ad7145);
    background-size: 2px 100%;
    background-position: 0 0, 100% 0;
    background-repeat: no-repeat;
}

/* title3 style */

.one3 .title3 {
    padding: 30px;
    font-size: 24px;
    color: #8b8b8b;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;

}

/* close style */

.close{
    color: #8b8b8b;
    font-size: 24px;
    position:absolute;
    left:-11px;
    top:-62px;
    z-index:3;
     border-top: 0.5px solid #1f1616;
    border-left: 0.5px solid #1f1616;
    border-right: 0.5px solid #1f1616;
    border-bottom: 0.5px solid #1f1616;
    padding:10px 17px;
    background-color:#212121;
    transition: 0.2s ease-in-out;
}
.close:hover{
    background-color: #8b8b8b;
    color:#212121;
    cursor:pointer;
    transition: 0.2s ease-in-out;
}

JavaScript:


function showDiv() {
  var x = document.getElementsByClassName("title3");
      if ( x.click === true ){
        document.getElementsByClassName("Content3").style.display = "block";
      }
}

Although there are no error messages, clicking on the .title3 div doesn't display the div with the class .Content3.

Answer №1

There are several issues in your code that need addressing

  1. You are using onmouseclick, which is invalid in Javascript. Use onclick instead.
  2. You are attempting to assign the HTML element with class title3 to variable x. Here are a couple of problems:

    2.1. You do not need to assign the clicked element to a variable within the function as you can access it directly with event.target

    2.2. By using getElementsByClassName, you're getting an HTML Collection, not a single element. It's better to use querySelector or add an id and use getElementById. However, utilizing event.target upon click is sufficient.

  3. if ( x.click === true ){ This check for element clicked status is redundant within a function triggered only by clicking on the element.

  4. Refer to point 2.2 regarding addressing elements correctly.

  5. Avoid naming HTML attributes with capital letters. Use content3 instead.

  6. Avoid importing jQuery if unnecessary in your project.

View the corrected code below

function showDiv() {
  document.querySelector(".Content3").style.display = "block";
}
.Content3 {
  display:none
  }
<div class="pseudo3">
  <div class="one3">
    <div class="Content3">
      <p class="close">X</p>
      <form action="order.php">
        <input type="text" value="First & Last Name">
        <input type="email" value="Your e-mail">
        <input type="text" value="Your phone number">
        <textarea>Write your feedback here</textarea>
        <button>Send</button>
      </form>
    </div>
    <div onclick="showDiv()" class="title3">
      FEEDBACK
    </div>
  </div>
</div>

Helpful links:

Answer №2

There's no need for jQuery in this scenario. Simply remove the onmouseover attribute and replace it with the following code snippet:

<script>
// Add a click listener to the .title3 element
document.getElementsByClassName("title3")[0].addEventListener('click', function(e){
   // Prevent the default action (not necessary here, but good practice)
   e.preventDefault(); 
   // Change the style to display the .Content3 element
   document.getElementsByClassName("Content3")[0].style.display = "block";
});
</script>

Answer №3

Is it possible to utilize the data property in relation to this particular subject?

<div class="titles">
    <button data-id="1">open 1</button>
    <button data-id="2">open 2</button>
    <button data-id="3">open 3</button>
</div>
<div class="contents">
    <p data-id="1">context</p>
    <p data-id="2">context</p>
    <p data-id="3">context</p>
</div>

Upon clicking any button, retrieve the data-id and perform actions within the contents div based on the respective data-id. If you are having trouble grasping the concept, I can provide an example for clarification.

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

Display the element only when the request sent with getJSON exceeds a certain threshold of time in milliseconds

Here's a snippet of my JavaScript code: surveyBusy.show(); $.getJSON(apiUrl + '/' + id) .done(function (data) { ... surveyBusy.hide(); }) .fail(function (jqXHR, textStatus, err) { ... surveyBusy. ...

Incorporate CSS animations prior to removing an element from an array

Before removing an item from my data table, I want to implement a CSS animation. The deletion is initiated by the @click event. I would like to preview the effect of my animation (class delete_animation) before proceeding with the actual removal. var vm ...

New and personalized bindings in knockout.js for dynamically updating a dropdown menu based on the selection in another dropdown menu

I have been using knockout for a few months now and have been getting along just fine. However, I recently encountered an issue where I cannot update the options within a SELECT tag because the ajax methods that retrieve data from the server are inside a ...

What methods are available to create distinctive, shareable links akin to those utilized by Zoom and Google Hangouts?

I'm currently developing a group video chat app and I'm facing the challenge of generating distinct shareable links for every chat room created. Can anyone guide me on how to accomplish this? My aim is for users to easily join the chat room when ...

Manipulating the DOM within an Angular application

What is the best way to perform DOM manipulation in Angular without using jQuery? Here is an example of code using jQuery: $(".next-step").click(function (e) { var $active = $('.wizard .nav-tabs li.active'); $active.next().removeClass(& ...

arranging data in html table columns using angular 2

I am facing a challenge where I require each column of a table to be sorted in ascending order every time it is clicked. The sorting logic implemented is a standard JavaScript method. While this method works well in most scenarios, it encounters issues whe ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...

Set up two separate tables with sufficient space in between each other

Is there a way to align these two tables next to each other with some space between them? Currently, they appear one below the other. How can I make them sit beside each other with spacing in between? If anyone knows how to do this, please help me out. &l ...

Guide on utilizing personalized fonts with Handlebars and Puppeteer

I have a Handlebar template that I am converting to PDF using Puppeteer. My question is how can I incorporate custom fonts? Currently, I have a static folder declared in my app.js file like this: app.use(express.static(path.join(__dirname, 'assets&ap ...

The loading animation does not appear in the NextJS 14 - loading.tsx component while a GET request is being processed

Component with 500 photos displayed on my page: 'use client'; import { useEffect, useState } from 'react'; import { wait } from '@/components/loaders/skeletons'; export default function Postings() { const [photos, setPhotos ...

What is the best way to extract the .text(data) value and use it within a conditional statement?

My goal here is to create a function that disables a button if a username exists, and enables it if the username is available. I'm not very experienced with JavaScript/jQuery, so I could use some help. Any assistance would be greatly appreciated: $(& ...

Manipulating an SVG file with JavaScript

Within the HTML code, there is a photo already added as an SVG file. I am interested in learning how to enable the user to select between two options - either a cross or a zero. Upon clicking on the designated area, the chosen figure should appear (resembl ...

Updating row values in an Angular table

I have a reusable table with the [cellData]="row" attribute to populate each cell on the table (see sample table in the screenshot). My question is, how can we replace the null values on the template with "---" so that instead of displ ...

Ways to verify the status within the DataTable?

Checking the condition inside column "data":"selectionAudit[0].assignFromDate" of a datatable to display content based on the conditions. var table4 = $('#auditAndNonAudit').DataTable({ "processing" : true, "scrollY": 100 ...

Angular's route resolve feature does not wait for the promise to resolve before

I just started using angular and I'm facing an issue with my user route. I'm trying to resolve the user object before rendering the view, but even after injecting $q and deferring the promise, the view is loading before the promise gets returned. ...

Activate function when list item is clicked

My goal is to execute a function when users click on the li elements in the snippet below without relying solely on onclick. For instance, clicking on the first li element (with a value of 1) should trigger a function where the value "1" is passed as an ar ...

What is the correct way to handle fetch timeouts in a React component?

Utilizing a JavaScript timeout, I am able to fetch Dogs from my API successfully. However, there are instances where the timeout fails to clear properly: import { useState, useEffect, useCallback } from 'react'; const DogsPage = () => { c ...

Django redirects to an alternative template instead of the default one

After renaming my login.html file to login1.html instead of deleting it, I have been using Django-registration and Django-registration-views from Github. However, despite this change, Django continues to call registration/login1.html. Is there a way for me ...

Apply the style when the page loads and remove it when clicked

There is a feature in my code that adds a class when an element with the class .tab is clicked. $(function() { $(".tab").click(function() { $(this).addClass('blueback'); $(".tab").not($(this)).removeClass('bl ...

Tips for adding data to an array while iterating through an object:

I have a task of looping through object results fetched from an API and pushing them into an array. historys: any = []; Here is how I am attempting to loop through the objects: Object.keys(response['orderdetail']).forEach(function(index, key) ...