I am having trouble getting my Jquery to locate the panelid

I tried following a tutorial to improve my coding skills, but I'm facing issues with my code. It seems like my jQuery isn't able to locate the panelid. I can successfully alert the panelids, but the functionality of clicking on "läs mer" and displaying text is not working as expected. The text should pop out when clicking on "läs mer" and change to "mindre-" . I'm feeling stuck and don't know where to go from here! This is driving me crazy.

The tutorial video: https://www.youtube.com/watch?v=Cc3K2jDdKTo

Html:

<ul>
    <li> <a data-panelid="panel1" class="showhide" href="#">Läs mer +</a> </li>
    <li> <a data-panelid="panel2" class="showhide" href="#">Läs mer +</a> </li>
    <li> <a data-panelid="panel3" class="showhide" href="#">Läs mer +</a> </li>
</ul>
<div id="panel1" class="textstyle">Ett enda bett från inlandstaipanen innehåller tillräckligt mycket gift för att döda upp till 100 vuxna människor eller 250 000 möss.</div>
<div id="panel2" class="textstyle">ouahsfouashfoas aushfaslal.</div>
<div id="panel3" class="textstyle">ioajsfoiasjgoiashfoas oahsgkmaspof.</div>

Jquery:

$(document).ready(function() {
    $(".showhide").click(function() {
        var panelId = $(this).attr('data-panelid')
        alert(panelId);
        var txt = $(this).text();
        $(panelId).toggle();
        if (txt == "Läs mer +") {
            $(this).text('Mindre -');
        } else {
            $(this).text('Läs mer +');
        }
    });
});

Thank you for everything :)

Answer №1

In order to target a specific element using jQuery, you must utilize the ID Selector (“#id”). Simply add the "#" symbol in front of the variable panelId.

$('#' + panelId)

For example, if your variable value is panel1, then calling $(panelId) will search for an element with the id of "panel1" which does not exist, resulting in it not functioning as expected.

Answer №2

Check out the functionality in action by visiting the jsfiddle link provided below.

http://jsfiddle.net/g4xd3u05/

$(document).ready(function() {
    $(".showhide").click(function() {
        var panelId = $(this).attr('data-panelid')
        var txt = $(this).text();
        $('#' + panelId).toggle(); //modification made here from just panelId
        if (txt == "Read more +") {
            $(this).text('Show less -');
        } else {
            $(this).text('Read more +');
        }
    });
});

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

Tips for Enhancing JavaScript Performance

Is there a way to enhance my JavaScript code like this: $(window).scroll(function() { if ($('#sec1').isVisible()) { $('.js-nav a.m1').addClass('active'); } else { $('.js-nav a.m1').removeClas ...

The formatter function provides the complete HTML markup for the slickgrid

Currently, I'm working on a project where I need to identify if a cell has been edited in slickgrid. To achieve this, I am attempting to utilize a custom formatter. function determineEdit(row, cell, value, columnDef, dataContext){ var varRow = da ...

Error: Your request could not be processed due to a Bad

url = "/IPM/KPI/Add"; input = new FormData($('#frmKPI').get(0)) ; PostAjax: function (isForm, url, input, divErrID, btnID, isSuccessFunction, isFailedFunction, NoModalAlert, isAsync) { var contentType = isForm ? false : "appli ...

jQuery reloads the page without refreshing the content

Currently, I am utilizing jQuery to send a form to a handler script via AJAX. After completion, the page is supposed to refresh automatically, but the content does not actually update unless the user does a Shift-F5 refresh on the browser. This can be conf ...

Managing cookies with ReactJs: A guide to setting, storing, and updating cookies without deleting the existing ones

How can I create a cookie that stores input values when the user submits a form, and updates the cookie without removing previously saved data on subsequent submissions? export default function saveToCookie() { const [ name, setName ] = useState('&a ...

position the div correctly above the table

I am currently working on creating a scheduler that has specific requirements: Show the working hours for each resource Show the interviews, allow changing the interview duration by resizing, and move the interviews using drag-and-drop functionality. I ...

my divs are not being affected by the max-width property and are retaining their

I've been learning CSS and HTML through an interesting tutorial on Udacity. Here's the code I've been working on: .image{ max-width: 50%; } .app{ display: flex; } .description{ color: red; max-width: 705px; } <h1 class="title" ...

Exploring the functionality of inline easing when using the ScrollTo plug-in

Attempting to utilize the ScrollTo plug-in with an easing effect. I prefer not to include the easing plug-in file, as I will only use it once and for a single easing effect. The specific 'easeOutBack' function I aim to implement is: easeOutBac ...

Unable to locate a contact within the state

Currently, I am diving into the world of React by exploring its documentation and challenging myself to build a small chat application. While I have a good grasp on the basics, I am encountering some issues with states. Within my code, there is an object ...

Ajax is working effectively as the first post is successful and the second post is able to retrieve data

UPDATE: I resolved the issue by relocating my form submitter script from the Header to the bottom of the jamesmsg.php page (the included one). By doing this, the functions are always re-loaded and attached to the "new" form each time the div is refreshed. ...

Converting a table-based layout to Bootstrap using the "row" and "col-*-*" classes

My current project is built on a table-layout structure, but now the requirements have changed and we need to make it responsive. To achieve this, we have decided to use Bootstrap. How can I convert the existing tables into a Bootstrap grid layout without ...

What is the best way to use CSS to adjust the width of an input type file?

I am looking to adjust the width of the HTML tag and also style the browse button in the input type file. In my search for solutions, I found: Is there a way to set width of input type file for showing in Firefox? and Setting uniform input type file wi ...

Managing JavaScript with Scrapy

Spider for reference: import scrapy from scrapy.spiders import Spider from scrapy.selector import Selector from script.items import ScriptItem class RunSpider(scrapy.Spider): name = "run" allowed_domains = ["stopitrightnow.com"] start_urls = ...

What is the best method for saving webcam-captured image paths into a MySQL database with PHP?

Is there a way to capture an image from the webcam of a user and store that image in a specified folder, while also saving the path of the captured image into a MySQL database using PHP? I am facing an issue where the webcam captured image path is not bein ...

What could be causing my website to resize when I test it offline versus when I upload it online?

I've been working on a new website and I keep all my files in a folder on my desktop for easy access. During the testing phase, I usually open the index page in various browsers to preview how it looks as I build it. Everything appeared correctly in F ...

Tips for displaying a dropdown on top of a modal with the help of Tailwind CSS

I am currently utilizing Tailwind CSS and I am struggling to display the white dropdown over my modal. Despite attempting to use the z-index, I have been unsuccessful in getting it to work. Do you have any suggestions or insights on how to resolve this is ...

Looking up the image directory in a JSON file on the fly - (Module not found...) React, Next.js

I'm attempting to dynamically retrieve data from a JSON file and insert it into a component. { "team": [ { "id": "", "name": "", "role": "", "bio": "", "major": "", "i ...

Utilizing useEffect to retrieve and display an empty array in a React component

I am currently developing a React application that leverages Fetch to retrieve data from an API using SQLite. Strangely, when I check the console, it only displays a length of 3 and Array[0]. This means I can't access data based on specific IDs like I ...

Is there any need for transpiling .ts files to .js when Node is capable of running .ts files directly?

If you are using node version 12, try running the following command: node hello.ts I'm curious about the purpose of installing typescript globally with npm: npm install -g typescript After that, compiling your TypeScript file to JavaScript with: ...

Make sure to wait for the complete loading of all content in the AJAX response before showing it on

I am currently working on a search function that sends a json request to the server for results every time a character is entered. Although this part is functioning correctly, I am trying to figure out how to add a loading class to .search-load > .conta ...