Is there a way to identify which paragraph element was clicked and retrieve its innerHTML content using JavaScript?

Hi there! I'm facing an issue where I need my webpage to identify which paragraph was clicked, retrieve its inner text, and then adjust the size of an image accordingly. You can check it out here: http://jsfiddle.net/YgL5Z/

Here is a snippet of my HTML:

<div class="one_of_4_colum"><p class="mysizeNum" onclick="mySize()">4</p></div>
  <div class="one_of_4_colum"><p class="mysizeNum" onclick="mySize()">3</p></div>
  <div class="one_of_4_colum"><p class="mysizeNum" onclick="mySize()">2</p></div>
  <div class="one_of_4_colum"><p class="mysizeNum" onclick="mySize()">1</p></div>
<img class="myPreviewElmo">

This is the corresponding JavaScript code:

function mySize()
        {
            if ((this.innerHTML) == "4") {
                $('.myPreviewElmo').css('height', '200px');
            }
            if (this.innerHTML == "3") {
                $('.myPreviewElmo').css('height', '150px');
            }
            if (this.innerHTML == "2") {
                $('.myPreviewElmo').css('height', '100px');
            }
            if (this.innerHTML == "1") {
                $('.myPreviewElmo').css('height', '50px');
            }
        }

Thank you for your help!

Answer №1

Here is a suggestion:

$(".clickSize").on("click", function() {
    var num = parseInt($(this).text());
    var newHeight = num * 50;
    $('.previewImage').css('height', newHeight + "px");
})

Answer №2

To start, avoid using on* event attributes as they are outdated and not ideal for separation of concerns. It is recommended to attach events in jQuery instead. Additionally, you can simplify your code by utilizing data-* attributes:

<div class="one_of_4_colum">
    <p class="mysizeNum" data-height="200px">4</p>
</div>
<div class="one_of_4_colum">
    <p class="mysizeNum" data-height="150px">3</p>
</div>
<div class="one_of_4_colum">
    <p class="mysizeNum" data-height="100px">2</p>
</div>
<div class="one_of_4_colum">
    <p class="mysizeNum" data-height="50px">1</p>
</div>
<div class="myPreviewElmo">
$('.mysizeNum').click(function () {
     $('.myPreviewElmo').css('height', $(this).data('height'));
});

Check out this example fiddle.

Answer №3

Make sure your HTML is structured like this -

<div class="one_of_4_colum"><p class="mysizeNum">4</p></div>
  <div class="one_of_4_colum"><p class="mysizeNum">3</p></div>
  <div class="one_of_4_colum"><p class="mysizeNum">2</p></div>
  <div class="one_of_4_colum"><p class="mysizeNum">1</p></div>
<div class="myPreviewElmo"></div>

And don't forget your javascript -

$(document).ready(function() {
    $('.mysizeNum').click(function() {
        $('.myPreviewElmo').height(parseInt($(this).text())*50);
    });
});

Also, ensure that you have enabled the jQuery library in your fiddle settings.

Answer №4

<div class="one_of_4_colum">
    <p class="mysizeNum" data-size="4">4</p>
</div>
<div class="one_of_4_colum">
    <p class="mysizeNum" data-size="3">3</p>
</div>
<div class="one_of_4_colum">
    <p class="mysizeNum" data-size="2">2</p>
</div>
<div class="one_of_4_colum">
    <p class="mysizeNum" data-size="1">1</p>
</div>
<div class="myPreviewElmo">

next,

jQuery(function () {
    var heights = {
        'size-1': '50px',
        'size-2': '100px',
        'size-3': '150px',
        'size-4': '200px'
    }
    $('.mysizeNum').click(function () {
        $('.myPreviewElmo').css('height', heights['size-' + $(this).data('size')]);
    })
})

Example: Fiddle

Answer №5

After analyzing your code, I found several issues and decided to rewrite most of it. You can find the updated version on this jsfiddle link - http://jsfiddle.net/YgL5Z/7/. Although there may still be room for improvement, the revised code effectively accomplishes the desired task.

$(function () {
    $(".mysizeNum").click(function() {
        var newheight=(parseInt($(this).text())*50);
        $('.myPreviewElmo').height(newheight);
    });
});

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

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

Using Strapi and Next.js to retrieve user information

After searching for similar questions with no luck, I'm reaching out for help. Building an authentication system using Strapi and Next.js, I'm faced with a task that seems simple but eludes me. The main question is: How can the client retrieve u ...

Transforming NodeJS Express HTTP responses into strings for AngularJS consumption

I have been working on creating an AngularJS program that communicates with an Express/Node.js API and a MySQL database. On the login page, I am successfully able to call the API which connects to MySQL. Depending on the correct combination of username an ...

Initiate the Bull Queue Process upon launching the Application

As I develop my API, I am setting up a queue and adding jobs to it. Additionally, I have configured the API to start processing these jobs as soon as they are added. const newQueue = createQueue(queueName, opts); newQueue.add('JokesJob', data, o ...

Utilizing custom links for AJAX to showcase targeted pages: a beginner's guide

I am putting the final touches on my website and realized that it may be difficult to promote specific sections of the site because the browser address never changes. When visitors click on links, they open in a div using Ajax coding. However, if I want to ...

Tips for accessing the firebase user's getIdToken method in Next.js after a page reload

Currently, I am developing a Next.js project and implementing user authentication using Firebase's signInWithPhoneNumber method for phone number verification. After successful verification, I receive a Firebase user with the getIdToken method to retri ...

Empty Canvas: Google Charts Graph Fails to Populate

I am currently using mysql, php, and javascript to display a curve chart. The issue I am facing is that the chart appears blank. google.load('visualization', '1.0', {'packages':['corechart']}); google.setOnLo ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...

What is the process for sharing your website content on Google Blogger?

I am currently developing a dashboard for a small business website and I would like to implement a feature that allows users to post directly to their Blogger blog from the dashboard of their own website. This eliminates the hassle of having to switch betw ...

There are times when window.onload doesn't do the trick, but using alert() can make

I recently posted a question related to this, so I apologize for reaching out again. I am struggling to grasp this concept as I am still in the process of learning JavaScript/HTML. Currently, I am loading an SVG into my HTML using SVGInject and implementi ...

Creating a customizable range input for pixel values: a step-by-step guide

I am looking to design a pixel range input. Here is an example: let slider = document.querySelector("input"); slider.addEventListener("change", () => { console.log(slider.value); }); <input type="range" min="5px" max="50px"> However, the r ...

Adding extra fields to an existing JSON response in a TypeScript REST API

I am in need of an additional column to be added to my response data. Currently, I am fetching data from multiple REST endpoints one by one and merging the results into a single JSON format to display them in an Angular Mat table. The columns that I want t ...

Having trouble getting the mock module to work with mockImplementation

I have been facing a challenge in properly testing this File. Some tests require mocking the entire module, while others only need specific methods mocked. I have tried various combinations, but currently, for one specific test below, I am attempting the f ...

Having trouble moving to a different component in Angular?

In my application, I am facing an issue with navigating from List to Details component by passing the ID parameter. It seems that there is no response or error when attempting to call the relevant method. Below, you can find the code snippets related to th ...

Adjust the size of a DIV once all AJAX requests have been completed within a .getScript function in JavaScript

I'm facing an issue with dynamically resizing a DIV after all content is loaded using jQuery. This is the structure of my HTML page: html <div id="limit" style="position: relative; overflow: hidden;"> <div class="contentpanel> ...

The issue with the Timber Ajax-cart drawer is that it fails to update the quantity of added or removed products

Check out my site: with the password set to "satin" I've integrated the Timber ajax-cart feature into my theme, but I'm facing an issue where the cart quantity doesn't update when clicking the "+" or "-" buttons in the drawer. Any help wo ...

Insert title into PDF document

I am currently working on a react application that generates PDF documents easily. The libraries I have utilized are: jspdf html2canvas Below is the code snippet that demonstrates my approach: index.js: <div className="App"> < ...

Creating an extra dialogue box when a button is clicked in React

Having an issue with displaying a loading screen pop-up. I have an imported component named LoadingDialog that should render when the state property "loading" is true. When a user clicks a button on the current component, it triggers an API call that chang ...

I am interested in using the split method to separate and then mapping an object in JavaScript

Need assistance on separating an array using the split method. The array contains objects with properties such as name, course1, course2, and course3. Only the courses with text in their content along with a plus sign should be separated into an array usin ...