Display a specific paragraph inside a div using jQuery

I am having trouble getting my jQuery code to display a specific paragraph when a particular div is clicked on.

My goal is for the content "v" to be displayed if the user clicks on the ".Virus" div, and for the contents of ".screenInfo" to be shown if the user clicks on the ".screenRepair" div. Any assistance with this would be greatly appreciated.

HTML:

<div class="outerService">
    <div class="service">
        <div class="virus" style="width: 230px; height: 208px;">
            <center>
                <h3 style="width:200px; text-align:center">Computer Virus</h3>
                <img src="images/Services/virus.jpg" alt="virus" height="140px"/>

            </center>
        </div>

        <div class="information">
            <p class="v">This is information</p>
            <p class="screenInfo">hello</p>
        </div>
        <div class="screenRepair" style="width: 230px;">
            <center>
                <h3 style="width:auto; text-align:center">Screen Replacement</h3>
                <img src="images/Services/smashedScreen.jpg" alt="BrokenScreen" height="140px"/>

            </center>
        </div>
    </div>
</div>

CSS:

.outerService {
    width: 90%;
    margin-left: auto;
    margin-right: auto;
    height: auto;
    border: 1px solid blue;
}

.service {
    display: table;
    height: auto;
    max-width: 1044px;
    margin-top: 20px;
    margin-bottom: 20px;
    margin-left: auto;
    margin-right: auto;
    border: 1px solid red;
}

.virus, .screenRepair, .hardwareRepair, .WindowsReinstall, .maintenance, .SoftwareRepair, .MemoryUpgrades, .DataRecovery {
    width: 250px;
    height: 208px;
    float: left;
    max-height: auto;
    text-align: center;
    margin-left: 10px;
    border: 1px solid #000;
}


#vInfo {
    float: none;
    width: 50%;
    text-align: justify;
    border: 1px solid #000;
    display: none;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 20px;
}

.information {
    margin-left: 10px;
    border: 3px solid green;
    margin-top: 230px;
    margin-bottom: 12px;
    height: 200px;
    max-width: 100%;
    display: none;
}

.information p {
    text-align: justify;
    margin-top: 20px;
    margin-left: 20px;
    margin-right: 20px;
}

jQuery

$(document).ready(function () {

$(".virus").click(function () {
$(".information .v").show();
});
});

Answer №1

If you want to enhance your current CSS, you might experiment with the following approach:

$(document).ready(function() {
    var $info = $( '.information' );
    $(".virus").click(function() {
        $info.show().find( 'p:not(.v)' ).hide().siblings().show();
    });

    $(".screenRepair").click(function() {
        $info.show().find( 'p:not(.screenInfo)' ).hide().siblings().show();
    });
});

Alternatively, you could modify your CSS slightly by attempting to hide every P within .information instead of hiding .information itself.

Trust this suggestion proves beneficial.

Answer №2

revise the properties of your information div in the css file by removing display:none

 .information {
      margin-left: 20px;
      border:5px solid blue;
      margin-top: 200px;
      margin-bottom: 15px;
      height: 250px;
      max-width: 90%;
 }

include these lines in your css as well

 .information .v {
       visibility: hidden;
 }

 .screenInfo{
       visibility: hidden;
 }

Answer №3

Use Toggle to easily display or hide a div element

You can try implementing it like this:

$(document).ready(function(){
    $('#button').on('click', function(event) {        
         $('#content').toggle('visible');
    });
});

Check out the working example on JS Fiddle

Answer №4

$(document).ready(function() {

            $(".cyber").click(function() {
                $(".details").show().find('span').show().next('.systemDetails').hide();
            });

             $(".systemFix").click(function() {
                $(".details").show().find('span').show().prev('.c').hide();
            });
 });

JSFiddle

Answer №5

Consider trying out this approach:

$(".service img").click(function () {
    $(".information .v").toggle($(this).closest('div').hasClass('virus'));
    $(".information .screenInfo").toggle($(this).closest('div').hasClass('screenRepair'));
});

.hasClass() will return either true or false.

If you use .toggle(true), it will show the hidden object, while .toggle(false) will hide it.


A helpful tip from the comments is to ensure all info divs are initially hidden within the .information div. If needed, display this one first before others.


You might also want to make some changes such as:

.virus, .screenRepair, .hardwareRepair, .WindowsReinstall, .maintenance, .SoftwareRepair, .MemoryUpgrades, .DataRecovery {
    width: 250px;
    height: 208px;
    float: left;
    max-height: auto;
    text-align: center;
    margin-left: 10px;
    border: 1px solid #000;
    display: none; /* Add this to initially hide the info divs. */
}

.information {
    margin-left: 10px;
    border: 3px solid green;
    margin-top: 230px;
    margin-bottom: 12px;
    height: 200px;
    max-width: 100%;
    display: none;
}

Add the following line as well:

$(".service img").click(function () {
    $(".information").show(); // Display it before showing any other div.
    $(".information .v").toggle($(this).closest('div').hasClass('virus'));
    $(".information .screenInfo").toggle($(this).closest('div').hasClass('screenRepair'));
});

You may want to take a look at this alternative:

$(".service > div:not(.information)").click(function () {
    $(".information").hide().show(); // Show it before displaying any other div.
    $(".information .v").toggle($(this).hasClass('virus'));
    $(".information .screenInfo").toggle($(this).hasClass('screenRepair'));
});

Answer №6

Give this a shot

$(document).ready(function () {
        $(".bug").click(function() {
            $(".details").show();
             $(".b").show();
            $(".displayInfo").hide();
        });

         $(".fixScreen").click(function() {
            $(".details").show();
             $(".displayInfo").show();
            $(".b").hide();
       });

});

Answer №7

view live demo

$(document).ready(function() {
            $('.bug').click(function() {
                $('.details').show();
                $('.b').show();
            });
        });

.details {display:none;} .details p{display:none;}

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

AJax and MVC: Elevating Your File Uploading Experience

I have come across numerous examples of file uploading, but most of them involve using forms or stand alone file uploads where only the file itself is passed. Currently, I have a page that sends data to a controller via Ajax. Now, I want to incorporate a ...

Is it possible to remove Sprites from a three.js scene?

Currently facing an issue where I am trying to update axis labels on a 3D plot by removing the old labels (implemented as sprites) before adding new ones. Unfortunately, I am experiencing difficulties. The previous labels seem to persist in the scene even ...

What method can be used to keep Chromium open while using Puppeteer?

I am trying to figure out how to launch only one instance of Chromium from my first script and then connect to it from subsequent scripts. I am aware of the puppeteer.connect() method, but the issue is that when I start the script responsible for launching ...

Turn off the hover effect for an HTML element

I'm trying to find a way to disable the hover state of my HTML element without using additional CSS to override the existing styles. Here's the code I currently have: <div id="test"> Hello world </div> <style> #test {c ...

Having issues with mouse hover not functioning on button in internet explorer 8?

Currently, I am working with asp.net mvc4 and encountering an issue where the button's color does not change when hovered over. The default blue focus always remains on the button. Can someone assist me in resolving this problem? I am using Internet E ...

What steps can I take to ensure my customized tab component can successfully pass an index to its children and effectively hide panes?

I'm currently working on developing a custom Tabs component to enhance my knowledge of React, but I seem to have hit a roadblock. The structure involves three key components that draw inspiration from Material-UI tabs: Tabs, Tab, and TabPane. Tabs.j ...

Having trouble toggling the navbar on and off in mobile. Error message: Unable to read parentnode of undefined

When I try to make my mobile navbar full screen on a mobile device, the hamburger button works as expected when clicked. Initially, all the links are displayed in full page view, but once I click on a link, it disappears and takes me to the respective sect ...

Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route: import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLI ...

What steps should I take to ensure the height of this navigation bar is correct?

I'm attempting to ensure that this div displays the correct height (without manually specifying a fixed number like 75px). Here's how I want it to appear: ------------------------------------------ | something | something else | --- ...

Could not locate the CSS file within the HTML document (404)

I've searched high and low on YouTube but can't seem to find a solution to this problem. Every time I run the code, it gives me an error message saying GET net::ERR_ABORTED 404 (NOT FOUND) <html> <head> <title>itays websit ...

Setting up React Native on a Mac M1 device

I am currently setting up React Native on my MacBook M1 Despite having installed npm, JDK, Node, Rosetta, CocoaPod, VSCode, Android Studio, Xcode and more, when I try to run the command (npm start), the directories for iOS and Android are not present. The ...

Attempting to transmit JavaScript information to my NodeJS server

Having some trouble sending geolocation data to NodeJS through a POST request. When I check the console log in my NodeJS code, it's just showing an empty object. I've already tested it with postman and had no issues receiving the data. The probl ...

Encountering issues with reading undefined properties while working with react-chartjs-2 and chart js

Having trouble with react chartjs errors? Visit the link for more details https://i.stack.imgur.com/lI2EP.png The versions I'm using are ^3.5.0 for chart.js and ^4.0.1 for react-chartjs-2 Tried downgrading to version 2 but it didn't solve the ...

Optimal approach to displaying views with Express.js and EJS

Recently, I came across a website that only renders EJS templates using Express.js routing. All the routes are defined in the /routes/index.js file. As the file grows with more routes being added, I am thinking about restructuring it to make it more develo ...

Adjust the height to match the shortest sibling child div height

In my layout, I have multiple rows with each row containing multiple columns. Within each column, there is a div and a paragraph - the div contains an image. My goal is to set the div with the class cover-bg to the lowest height of cover-bg in the same row ...

Use Node.js to transform every spreadsheet into Json format

I have been attempting to convert an Excel file into JSON format. I tried utilizing the "xls-to-json" npm package with the following code: node_xj = require("xls-to-json"); node_xj({ input: "Auto.xlsx", // input xls output: "output.json", // output ...

Every time I attempt to log into my app, I encounter a persistent 401 error message

I've implemented a user/login route that retrieves a user, compares their password with a hashed version, creates a token, and sends it to the front end. However, I encountered a persistent 401 error in the console on the front end, leading to the fin ...

Is there an alternative method to handle the retrieval of JSON data without encountering numerous errors?

I'm currently in the process of instructing an LLM model to generate a blog. I used Mistral as the base model and set up an instruction to return JSON output. I then created a function that takes the prompt as an argument and returns generatedPosts as ...

Unexpected behavior from Jquery

Users can select options that reveal more choices and text boxes upon clicking. Despite copying and pasting the code for all options, one specific part is not working as expected. The rest of the options function correctly. The code snippet causing issue ...

The system seems to be having trouble locating the password property, as it is returning a value of

I'm currently working on a database project using MongoDB and Node.js. I'm trying to update a specific field, but unfortunately I keep getting an error. The model I am working with is called "ListaSalas": router.post('/updatesala', fun ...