The functionality of Inettuts within JavaScript seems to malfunction whenever I attempt to reposition the div

I developed a widget framework using inettuts and integrated database functionalities with ajax in asp.net and sqlserver. Widgets are dynamically loaded based on user data from the database, but I encountered an issue when trying to move a widget - the JavaScript inside it stops working. Below are the code snippets, can you identify what might be causing this problem?

<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
    jQuery(".c").hide();
    jQuery("#widgetbodycontainer").click(function(e) {
        console.log("clicked");
        // if user clicks on a .c element or a descendant of one
        if (jQuery(e.target).hasClass("h") || jQuery(e.target).parents(".h").length) {
            jQuery(e.target).next(".c").slideToggle(200);
        }
    });
});

</script>

<div id="container">
    <div id="widgetbodycontainer" >
        <div class="layer1">
            <p class="h">Company </p>
            <div class="c">
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></div>
            <p class="h">Person</p>
            <div class="c">
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></div>
            <p class="h">Result</p>
            <div class="c"></div>
        </div>
    </div>
</div>

Answer №1

It is likely that your ajax behavior is replacing elements, which in turn destroys any event handlers directly connected to them. To solve this issue, you should implement event delegation, where a "smart" handler is attached to a suitable parent container. Here's an example:

// utilizing jQuery 1.7 onwards
jQuery("#widgetbodycontainer").on("click", ".h", function () {
    jQuery(this).next(".c").slideToggle(200);
});

UPDATE: If you are using an older version of jQuery, you'll need to implement event delegation the traditional way:

jQuery("#widgetbodycontainer").click(function(e) {
    console.log("clicked");
    // check if user clicked on a .c element or its descendant
    if (jQuery(e.target).hasClass("h") || jQuery(e.target).parents(".h").length) {
        jQuery(e.target).next(".c").slideToggle(200);
    }
});​

Check out the demo here.

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

Manipulate jQuery to set the table row containing empty table data cells to be lower than the row with

I am using HTML and jQuery to sort my table, including non-standard sorting with multi-tbody. The issue I am facing is that the prices (Цена) in the td are sorted ascending but not correctly. Why is this happening? Additionally, I need to move the tr&a ...

What strategies can I use to dynamically update the .active class in jquery so it doesn't only target the initial one?

Utilizing bootstrap for tab-fade functionality has been successful so far. However, I am facing an issue when trying to select multiple active classes instead of just one. My current JQuery code only changes the text in the first element with the "active" ...

Inability to load a MySQL table using Ajax on the same webpage

I'm facing an issue where I want to load a table from mySql on the same page without getting redirected to another page. The user selects a date range, and upon pressing submit, it should appear in the designated div id tag. However, the functionality ...

What could be causing my AJAX code to fail in retrieving information from an API?

Hey everyone, I'm new here and hoping to get some help with an issue I'm facing. I've written a code to fetch data from an API and display it on my HTML page, but for some reason the AJAX code isn't working. There's nothing showing ...

Breaking down ZipFile into numerous smaller fragments and then reassembling those fragments to reconstruct the original ZipFile

I am facing an issue while trying to transfer a large zip file to a remote server. In order to overcome this problem, I have attempted to split the zip file into smaller chunks and send these individual pieces to the remote server. However, upon combining ...

The query limit issue in Sails JS

I am encountering a 413 (Request Entity too large) error when making a request to a Sails Js app (v0.12). Despite my attempts to raise the request limit in the bodyParser, I have not seen any changes take effect. In config/http.js, I included a customize ...

Merging object keys and values from JSON arrays based on their keys, using JavaScript

Is there a way to merge object keys' values from JSON arrays based on their key? json1 = [ {key:'xyz', value:['a','b']}, {key:'pqrs', value:['x','y']} ] json2 = ...

Tips and tricks for seamlessly aligning a specific section of your webpage to ensure it scrolls smoothly into view

My codes are not being centered when I use smooth scrolling on a specific section of a Bootstrap carousel template. Is there an easier way to achieve this? The explanation in a post from six years ago didn't help much. Here are my codes and screenshot ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

Generate a div dynamically and incorporate a function that triggers on click event dynamically

In my current project, I am faced with a challenge due to laziness. My goal is to automatically generate menu buttons that are linked to different sections of a page using raw JavaScript. The issue arises when the body content of my site is loaded from an ...

What is the best way to retrieve the Axios response using Express?

I've recently delved into working with Express and I'm currently struggling with making an Axios request using route parameters, and then updating some local variables based on the response. Here's a snippet of what I've been working on ...

The initialization of a static member in a JS class occurs prior to the loading of the cdn

After declaring this class member, I encountered the issue stating that MenuItem is not defined. It appears that the class initialization occurs before React or Material-UI finishes loading (I am currently loading them from their CDN using straight < ...

Methods like jQuery blink(), strike(), and bold() offer dynamic ways to manipulate

I'm currently tackling an inquiry. The code I crafted seems to be functioning without any issues: (function () { if($('#target:contains("bold")')) { $('#target span:first').css('font-weight','bold ...

Experiencing an inexplicable blurring effect on the modal window

Introduction - I've implemented a feature where multiple modal windows can be opened on top of each other and closed sequentially. Recently, I added a blur effect that makes the background go blurry when a modal window is open. Subsequently opening an ...

infinite loop issue with beforeRouteEnter

I'm experiencing an issue with Vue Router. The scenario is to load / initially, retrieve data from there, and then navigate to the /chat/:chatId route to display the interface using the :chatId parameter obtained from an API. The routes configured a ...

During the rendering process, the property "instance" was attempted to be accessed but is not defined

I am having trouble creating a Contact Us page using v-model. My code keeps throwing these errors: Property "inputted_name" was accessed during render but is not defined on instance Property "inputted_email" was accessed during render but is not defined o ...

JavaScript enables the deletion of a class

In HTML 2, I am able to show different statements based on the scenario. These statements are styled using the Bootstrap alert class. The goal is to ensure that when new data is sent, any old communication disappears without causing overload on the page. ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...

Incorporating Common Types for Multiple Uses

Is there a way to efficiently store and reuse typings for multiple React components that share the same props? Consider the following: before: import * as React from 'react'; interface AnotherButtonProps { disabled?: boolean; onClick: (ev ...

Mastering the alignment of Material-UI Menu items

When using the menu and menu item components of material-ui to create a select dropdown menu, I encountered an unusual issue where the dropdown menu always expands to the left side of the box, as shown in the image below: https://i.stack.imgur.com/ykRrp.jp ...