Display and conceal individual divs using jQuery

Despite my lack of experience with jQuery, I am struggling with even the simplest tasks.

The goal is to display/hide specific messages when certain icons are clicked. Here is the HTML code:

<div class="container">
    <div class="row">
        <div class ="col-md-2 pov_icon">
            <div class="pov_icon_small" value="measure">
                <i class="fa fa-clock-o"></i>
            </div>
            <div class="pov_title_small">
                MEASURE
            </div>
        </div>

        <div class ="col-md-2 pov_icon">
            <div class="pov_icon_large" value="locate">
                <i class="fa fa-map-marker"></i>
            </div>
            <div class="pov_title_large">
                LOCATE
            </div>
        </div>

        <div class ="col-md-2 pov_icon">
            <div class="pov_icon_small" value="inform">
                <i class="fa fa-commenting"></i>
            </div>
            <div class="pov_title_small">
                INFORM
            </div>
        </div>

        <div id="measure" style="display:none" class="pov_description">
            <p> Message MESSAGE</p>
        </div>
        <div id="locate" class="pov_description">
            <p> Message LOCATE</p>
        </div>
        <div id="inform" style="display:none" class="pov_description">
            <p> Message INFORM</p>
        </div>

    </div>
</div>

The JavaScript code for changing the classes of pov icon/title works as intended and is included below:

$('.pov_icon_small , .pov_icon_large').on('click', function () {
    $('.pov_icon_large').not($(this)).removeClass('pov_icon_large').addClass('pov_icon_small');
    $('.pov_title_large').not($(this).next('div[class^="pov_title_"]')).removeClass('pov_title_large').addClass('pov_title_small'); 
    $(this).toggleClass("pov_icon_small").toggleClass("pov_icon_large");
    $(this).next('div[class^="pov_title_"]').toggleClass("pov_title_small").toggleClass("pov_title_large");
});

The objective is to show a specific message (e.g., Message Measure) when a certain icon

pov_icon_small value="measure"
is clicked while hiding the rest. When another icon is clicked, its respective message should be displayed while the others are hidden:

$(document).ready(function(){
    $('input[.pov_icon_small]').click(function(){
        if($(this).attr("value")=="measure"){
            $(".pov_description").not("#measure").hide();
            $("#measure").show();
        }
        if($(this).attr("value")=="locate"){
            $(".pov_description").not("#locate").hide();
            $("#locate").show();
        }
        if($(this).attr("value")=="inform"){
            $(".pov_description").not("#inform").hide();
            $("#inform").show();
        }
    });

It seems that the script linking the messages isn't functioning. Is there an error in my approach, or should I be structuring the code differently?

Answer №1

There are a couple of issues here. Firstly, your CSS selector input[.pov_icon_small] is not valid. Secondly, you have attached the click function to elements with the class pov_icon_small, which do not have sufficient height or width for users to click on. I have made adjustments to the HTML so that the click event now binds to elements with the class pov_title_small.

To make sure your click function works properly, you should attach it to items that have a value assigned to them and then pass that value as the selector. In this case, I have changed the attribute from value to data-value for elements with the class pov_title_small. The click function now uses this data value to select the ID you want to display.

Here is the updated code:

HTML:

<div class="container">
<div class="row">
<div class ="col-md-2 pov_icon">
 <div class="pov_icon_small">
  <i class="fa fa-clock-o"></i>
 </div>
 <div class="pov_title_small" data-value="measure">
   MEASURE
 </div>
</div>

<div class ="col-md-2 pov_icon">
 <div class="pov_icon_large">
  <i class="fa fa-map-marker"></i>
 </div>
 <div class="pov_title_large" data-value="locate">
   LOCATE
 </div>
</div>

<div class ="col-md-2 pov_icon">
 <div class="pov_icon_small">
  <i class="fa fa-commenting"></i>
 </div>
 <div class="pov_title_small" data-value="inform">
   INFORM
 </div>
</div>

<div id="measure" style="display:none" class="pov_description">
 <p> Message MESSAGE</p>
</div>
<div id="locate" style="display: none;" class="pov_description">
 <p> Message LOCATE</p>
</div>
<div id="inform" style="display:none" class="pov_description">
 <p> Message INFORM</p>
</div>

Javascript:

$(document).ready(function(){
    $('[data-value]').bind('click', function(){
        $('.pov_description').hide();
        $('#'+$(this).attr('data-value')).show();
    });
});

You can see the updated functionality in action in this JS Fiddle: http://jsfiddle.net/h97fg75s/

Answer №2

First step: Start by obtaining a value and converting it to an id.

Second point: As @juvian pointed out, $('input[.pov_icon_small]') is not a valid selector.

Third note: The selector .pov_icon_small refers to a div, not an input, so you should use $('div.pov_icon_small') instead.

Fourth consideration: While .pov_icon_small does not have a value attribute, .pov_title_small and .pov_title_large do have a value attribute.

$(document).ready(function(){
  $('div.pov_title_small , div.pov_title_large').click(function(){
    var ThisValue = $.trim($(this).attr('value'));
    $(".pov_description").not("#"+ThisValue).hide();
    $("#"+ThisValue).slideToggle()
  });
});

See Working Demo

If you want to control it from .pov_icon, you have two options:

Option one: Add a value attribute to .pov_icon_small/large.

Option two: Use

$('div.pov_icon_small , div.pov_icon_large').click

and

var ThisValue = $.trim($(this).next('div[class^="pov_title_"]').attr('value'));

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

Creating multiple divs with input fields dynamically using JavaScript is a useful skill to have

I need to generate 3 input text boxes for gathering user input on names and email addresses. These inputs must be created dynamically, meaning that as the user clicks on the email input field, a new line with all three elements should be generated. Below i ...

Tips for troubleshooting a node module that is part of a build process

When working on my applications, I often rely on the NPM package.json to handle my build tools. However, I've come across a module that seems to have a bug. I'm eager to debug it, but I'm unsure how to do so within the context of the build t ...

Determining When to Activate Button Based on Angular - Verifying That All Choices Have Been Ch

This quiz application requires the user to choose options before proceeding to the next page, with the next button being disabled by default. Once all options are chosen, the next button should become enabled. NOTE: Although the functionality for selecti ...

What is the best way to create fading text effects in an AngularJS application?

Running an AngularJS web application that showcases three words for 5 seconds each: Hello, World & Goodbye. The controller setup is as follows: self.currentIndex = 0; self.myTexts = ['Hello', 'World', 'Goodbye']; self.cu ...

Is it possible to add to JSON formatting?

Here is the JSON object I have: new Ajax.Request(url, { method: 'post', contentType: "application/x-www-form-urlencoded", parameters: { "javax.faces.ViewState": encodedViewState, "client-id": options._clientId, ...

Invisible enigmatic anomaly detected on non-existent line within the realm of Node.js

Today, when I tried to run my app on node, it encountered an unexpected token error at line 219 in the file. The full error log is as follows: syberic@syberic:~/Web/lotalot$ node app.js /home/syberic/Web/lotalot/config/passport.js:219 }); ^ SyntaxError: ...

Are the references to clip-path: path() on MDN and other sources inaccurate?

I'm attempting to achieve a simple task by using clip-path with the path property and having it scale to fit the entire size of the containing div. After researching extensively, I came across mentions of the [geometry-box] property in some places, bu ...

Pass an array of files from a Jquery ajax request to a controller action

I am facing an issue where I can successfully pass a single file as System.Web.HttpPostedFileBase, but when attempting to pass an array of files, the controller's action receives null. I have attempted sending an array of files. HTML: <i ...

Dynamically sending data to child components in Vue.js

I'm currently working on a progress bar implementation where the progress status is determined by the submitAction method. The value for the progress bar is constantly being updated in this method. Here's my code: 1. Parent Component <templa ...

Is there a way to conceal the scrollbar while still permitting scrolling?

I'm interested in creating a custom scrollbar, but in order to do so I need to hide the default scrollbar while still allowing scrolling functionality. I've attempted: overflow-y:hidden; but this method hides the scrollbar and prevents scrolli ...

Changing styles using jQuery when hovering over an element

Here is an example of HTML code: <li> <p> <a href="#" class="link" ><img src="images/photo_cityguild_cropped.jpg" alt="Education" title="Education"> <span class="label">E D U C A T I O N</span> </ ...

Only the initial AJAX request is successful, while subsequent requests fail to execute

I am facing an issue with multiple inputs, each requiring a separate AJAX request. < script type = "text/javascript" > $(document).ready(function() { $("#id_1").change(function() { var rating1 = $(this).v ...

Black textures with images sourced from the same domain - Cross-origin

Despite trying numerous solutions and tips to resolve the cross-origin issue, I still can't seem to fix it. There are no errors, the images are hosted on the same domain as the webgl test, but the textures appear black. Occasionally when I refresh rep ...

Material UI Table dynamically updates with Firestore real-time data

My current code aims to update a Material UI table in real-time with data from a Firestore database. I can fetch the data and store it in an array, but when I assign this array to the table data, nothing changes. I've heard that I should use states fo ...

Issues with hover functionality in React Material Design Icons have been identified

I'm facing an issue with the mdi-react icons where the hovering behavior is inconsistent. It seems to work sometimes and other times it doesn't. import MagnifyPlusOutline from "mdi-react/MagnifyPlusOutlineIcon"; import MagnifyMinusOutli ...

Encountering a problem with Chrome Extension localization upon installation - receiving an error message claiming default locale was not specified, despite having

Error Message: "The package has been deemed invalid due to the following reason: 'Localization was utilized, however default_locale was not specified in the manifest.' Issue: I have developed a customized extension and defined a default locale, ...

Launching a HTML hyperlink inside a div with the power of jQuery

I am currently exploring the functionality of dragging and dropping an HTML link into a div element. My objective is to have the link open within that specific div element. The layout consists of two divisions named "left-panel" and "canvas". The concept ...

Create a unique functionality by assigning multiple event handlers to a single event

I am looking to add a JavaScript function to an event that already has a handler function. The new function should complement the existing one rather than replace it. For instance: There is a function named exFunction() that is currently linked to docume ...

Can you switch out the double quotation marks for single quotation marks?

I've been struggling to replace every double quote in a string with a single quote. Here's what I have tried: const str = '1998: merger by absorption of Scac-Delmas-Vieljeux by Bolloré Technologies to become \"Bolloré.'; console ...

Is it possible to create a hyperlink in the <button> element?

Having been immersed in HTML5 for quite a while now, I recently encountered a challenge while working on my login/register page project. I wanted to create a button that would redirect me to another HTML page upon clicking. While I am familiar with the < ...