jQuery: Function is not running as expected

I'm facing a challenge in executing a function twice, and I'm having trouble identifying the issue. Check out my JSFiddle at the following link: http://jsfiddle.net/g6PLu/3/

Javascript

function truncate() {
    $(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
}

$('div').each(truncate);

$('.truncate').click(function() {

if ($(this).parent().hasClass('closed')) {
    $(this).parent().removeClass('closed').addClass('open').children().show();
}

else if ($(this).parent().hasClass('open')) {
    $(this).parent().removeClass('open').addClass('closed');
    $('div').each(truncate);
    $(this).show();
}

});

The issue lies on line 15, where I invoke $('div').each(truncate); for the second time. It appears that it's not executing as expected. Any insights on how to resolve this?

Answer №1

It appears that you may be overcomplicating a straightforward task. Utilizing classes to display or hide content with CSS can simplify the process (especially since you are already adding the classes but not utilizing them).

Consider this more streamlined approach:

Simple CSS

.closed p { display: none; }
.closed p:nth-child(2) { display: block; }

JavaScript

$('div').addClass('closed');
$('.truncate').click(function() {
    $(this).closest('div').toggleClass('closed');
});

http://jsfiddle.net/g6PLu/9/

Answer №2

Whenever the show function is called, the paragraph tag <p> is modified to

<p style="display: block; ">
, which is why you must also call the hide method or remove that style attribute.

Do you think this is the expected behavior?

else if ($(this).parent().hasClass('open')) {
    $(this).parent().removeClass('open').addClass('closed').children().hide();
    $('div').each(truncate);
    $(this).show();
}

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

Save the user input to a dedicated text file

I am working with a couple of select tags that generate an array. Previously, I was only logging the array to the console upon pressing the SUBMIT button, but now I want to save it to a separate text file. Here is my main.html code: <form method="POS ...

Acquiring the content of elements contained within a div container

On a webpage, I have included multiple div elements with unique IDs and the following structure: <div class="alert alert-info" id="1"> <p><b><span class="adName">Name</span></b><br> ...

How can I ensure text remains confined within the parent div when working with Bootstrap?

I'm having trouble keeping the text and links within their parent div. Even though I set the outer boundary as col-sm-8, the text and links are overflowing. I'm not sure what I'm doing wrong, but the code I am using is shown below. I have a ...

File not found: The specified file 'C:Self Project eact-shopper eact-shopperclientuildindex.html' does not exist

I followed the tutorial and startup code by Reed Barger exactly, but every time I try to run the server I encounter this error: Error: ENOENT: no such file or directory, stat 'C:\Self Project\react-shopper\react-shopper\client&bso ...

React higher order component (HOC) DOM attributes are causing the error message 'Unknown event handler property' to be triggered

I recently created a Higher Order Component (HOC) using recompose, but I'm encountering a React Warning every time the props are passed down. Warning: Unknown event handler property `onSaveChanges`. It will be ignored. All my properties with a speci ...

Reinitializing a form with jQuery validation inside a modal box

While utilizing jQuery Validate in a form within a jQuery dialog, I am encountering an issue. Upon closing the dialog, I aim to clear all form fields and reset any fields with error feedback displayed. Although the fields are being reset to blank as expec ...

Develop a personalized API using Strapi that involves integrating data from two distinct tables

I am relatively new to Strapi, so please forgive my lack of experience. My goal is to set up a custom route for retrieving complex data using two related tables. I have relationships with the "items" and "comments" tables. My approach involves selecting ...

What is the best way to pass the reference of the p tag every time the button is clicked?

This is the code I used to create a button: <button type="submit" id="likebtn" onclick="likedpost(this) " data-postid="<%=blog._id%>" data-author="<%=user.username%>">Like</button> ...

Can a website be designed to render consistently across all browsers without relying on a CSS reset?

Is it possible to create a website that renders well across all browsers without using CSS reset? Should CSS reset be used for websites of all sizes - small, one-page, large? Is it better to write all the CSS without a reset and only address necessary rend ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...

jQuery script to update the image element of testimonials without caching

There is an issue with the image element not loading properly at times. <img class="picture" src="pic/car.jpg" alt="car"> To address this problem, a solution using jQuery to prevent caching and reload the image was implemented: $(".picture").attr( ...

What could be causing the triggering of two AJAX requests in the given JavaScript code?

I have a code snippet that fetches data from the server. I want to trigger it on document.ready(). My expectation is that the first request is sent to the server, receives a response, and then the second request is made, and so forth. However, when I insp ...

Retrieve the border color using Selenium WebDriver

Hey everyone, I'm currently trying to retrieve the border color of an extjs 4.2 form control text field using the getCssValue method. However, I'm having trouble getting the value as it's coming back blank. Below is a sample of my code that ...

Exploring JSON Data with Mustache Templates

Dealing with a significantly large JSON object that I can't control, I'm struggling to output a list of records (related to people in this case) using Mustache.js. Despite simplifying the complex object into a more manageable one with just the ne ...

Attempting to refresh Facebook Open Graph meta tags through client-side jquery and ajax requests

My current approach involves using ajax to load a content page containing a Facebook Like Button plugin. However, I am encountering an issue regarding the extraction of meta information by Facebook when a user likes the page. I am unsure of how to assign ...

Safari does not support SVG fill pattern, unlike Firefox and Chrome

Having an issue with Safari 6.1.5 not displaying a pattern in an SVG rectangle. After simplifying the code, here is the test case: <html> <head> <style> .patterned { fill: url("#myid") none; stroke:blue} ...

Converting a JavaScript object into JSON format

I am currently working on serializing a JavaScript object to JSON. Here is the code I have written so far: var info = {}; ... $.each(data, function (key, value) { info["name"] = value.name; info["id"] = value.id; ...

Angular is having trouble with the dropdown feature when using Semantic UI

I'm having trouble with the dropdown not displaying any items when I click on it. Here is the source code for reference: <div class = "ui centered grid"> <div class = "ten wide column"> <form class = "ui form"> <h4 cl ...

Activate a timer as soon as the page is first loaded. The timer must continue running from the initial load even if the user leaves

Looking to implement a time-limited offer on the first stage of our checkout process. The timer should start at 5 minutes when the page loads and continue counting down even if the user leaves the page and returns. Has anyone come across a script that can ...

Is there a way to extract all the content from a webpage's body using BeautifulSoup?

Looking to extract text from a medical document webpage for a Natural Language Processing project using BeautifulSoup, but encountering challenges. The specific website in question is located here: The goal is to capture the entire text body by utilizing ...