What is the process for getting non-event javascript instructions to function properly once a DOM element has been added

After inserting DOM elements (such as an AJAX response), event-delegation is necessary to ensure that events work properly. But what about basic JavaScript instructions?

All instructions are organized by affected PHP page to simplify code updates and avoid repetition. I want to test the existence of a specific class that is added dynamically after the JS file is loaded.

Example:

// NAVBAR.PHP

if ($('.className').length) {

$('.button-navbar').show(); }      

 /* FOOTER.PHP
 .... */

// VIEW_NEWS.PHP

$('.ajax_wrapper').on('click', '#view_news tr', function() {

    var id = $(this).attr("id");
    var get_news_request = $.ajax({type: "GET", url: "view_news.php", data: {news_id: id}, dataType: "html"});

    get_news_request.done(function(html) {

        $('.ajax_wrapper').hide('slide', {direction: 'right'}, function(){

            $('.ajax_wrapper').empty();
            $('.ajax_wrapper').hide().html(html);
            $('.ajax_wrapper').show('slide');

        });

    });

    get_news_request.fail(function(jqXHR, textStatus, errorThrown) {

        alert( "Request failed: " + textStatus + " " + errorThrown );
    });

});

Unfortunately, the condition shown below is not being executed even though the class now exists:

if($('.className').length) {

$('.button-navbar').show(); } 

Do you have a solution that does not disrupt the overall structure of the JS file?

Answer №1

The code provided does not function as an event handler or establish a lasting rule. It is simply procedural code that will not automatically trigger again once executed. When it ran, there was no such class present. Adding a class will not cause the code to run again.

To address this issue, you can manually check in both instances (at the start and within the ajax callback). To prevent redundant code, consolidate the shared functionality into a defined function:

function show_navbar_check() {
    if ( $('.className').length)
        $('.button-navbar').show();
}

show_navbar_check();

Then, invoke this function within the ajax callback as well:

$('.ajax_wrapper').on('click', '#view_news tr', function() {

    var id = $(this).attr("id");
    var get_news_request = $.ajax({type: "GET", url: "view_news.php", data: {news_id: id}, dataType: "html"});

    get_news_request.done(function(html) {

        $('.ajax_wrapper').hide('slide', {direction: 'right'}, function(){

            $('.ajax_wrapper').empty();
            $('.ajax_wrapper').hide().html(html);
            $('.ajax_wrapper').show('slide');

            /* Additional line added below */
            show_navbar_check();
        });

    });

    get_news_request.fail(function(jqXHR, textStatus, errorThrown) {

        alert( "Request failed: " + textStatus + " " + errorThrown );
    });

});

Side note: Another solution utilizing jQuery.live() exists for this problem, but I opted not to include it as I believe the above approach is more effective, partly due to efficiency considerations.

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

Validation of Button Groups and Automatic Disabling after Initial Click with HTML, CSS, and JavaScript

Criteria: Upon clicking a button from the selection of four buttons, all other buttons should become disabled except for the Next button. An alert window must appear when the Next button is clicked without selecting any other buttons, preventing navigatio ...

Achieving a Full-Screen Three.js Canvas in React: A step-by-step guide on spanning the view height and width of a webpage

I've been working on tweaking the code found in this particular example: How to connect Threejs to React? This is the snippet of code I am focusing on: import React, { Component } from 'react' import * as THREE from 'three' clas ...

Extract data from nested JSON and populate a list with corresponding values

<ul> <li><a href="" class="edit">a unique item in the list</a></li> <li><a href="" class="edit">another unique item in the list</a></li> <li><a href="" class="edit">yet another unique ...

Generate a fresh JSON object following a click event triggered by an HTTP PUT request

I have the following structure in JSON format: "disputes": [ { id: "", negotiation_type: "", history:{ user_flag: "", created_at: "", updated_at: "", created_by: null, updated_by: null, ...

The image fails to appear while creating a PDF in AngularJS using pdfmake

I recently started using a fantastic pdf printing library called pdfmake in my angularjs SPA to generate PDF files. Everything was going smoothly until I tried to include images in the PDF. Strangely, when I added images, nothing happened - no errors, no e ...

Declare the push method within the Countly.q array in a TypeScript declaration file

Is there a way to declare Countly push add_event method in the following manner? Countly.q.push(['add_event',{ "key":"action_open_web", }]); I attempted to do this inside a declaration file (.d.ts) but it did not work. Here ...

The functionality of fetching website titles using Ajax/jQuery is experiencing some limitations

Below is a code snippet for a simple website title getter: $( document ).ready(function() { $("#title").click(function() { var SubURL = $("#input").val(); $.ajax({ url: "http://textance.herokuapp.com/title/"+SubURL+"/", complete: function(da ...

The Vue JS Option element requires the "selected" attribute to be utilized as a property instead

I'm attempting to automatically have an option selected if the "selected" property is present on the option object. Here is my code snippet: <template> <select v-model="model" :placeholder="placeholder"> <option v-for="opt ...

Interact as a Votable Ajax Mishap

After delving into Ruby and experimenting with a demo application, I integrated the acts_as_votable gem. It's working well, but there's one key element missing - ajax. Constantly refreshing the page is becoming a hassle, so I attempted to incorpo ...

Unable to locate phonepe.intentsdk.android.release:IntentSDK:2.4.1 while integrating React Native

android build gradle : // Configuration options for all sub-projects/modules are defined in the top-level build file. buildscript { ext { buildToolsVersion = "33.0.0" minSdkVersion = 21 compileSdkVersion = 33 targetSdkVersion = ...

`Is there a way to dynamically update a nested field object in Mongoose without updating the entire object?`

const userProfile = new Schema({ name: { type: String, default: null }, contacts: { mobileNumber: { countryCode: { type: String, default: null }, digits: { type: String, default: null } }, email: { type: String, default: null }, facebook: { ...

ApolloError: Undefined fragment detected and unable to be used

Within the complex structure of my application, I encounter the following: import { gql } from '@apollo/client'; gql` fragment StuffTable on Stuff { id status } `; export const GetStuffDocument = gql` query GetStuff($id: ID!) { ...

The propagation of SVG events from embedded images via the <image> elements

I'm currently developing a diagramming tool using HTML, CSS, and Javascript with SVG for the drawing canvas. This tool consists of predefined "building blocks" that users can place on the canvas, rather than allowing free-hand drawing of shapes. Each ...

Is it feasible to conceal certain parameters within a URL using Angular UI Router?

Looking to pass two values to a new ui-view via parameters: item id list of objects However, I want the new view to display only the id in the browser URL and not the stringified array of objects: http://www.myapp.com/#/my-view/4 INSTEAD OF http://ww ...

Discovering every element on a webpage

Searching for elements in a webpage can be done using different methods. document.getElementsByTagName('*') and document.all Are there any other more efficient ways or are these two the most recommended? I am currently working on an element se ...

Determining the current element's index as I scroll - using Jquery

If I have a series of divs with the class name 'class' that are fixed height and enable auto-scrolling, how can I determine the index of the current 'class' div I am scrolling in? Here is an example: var currentIndex = -1; $(window).sc ...

Issue: The component factory for GoogleCardLayout2 cannot be located

Recently I've been working on an Ionic 3 with Angular 6 template app where I encountered an issue while trying to redirect the user to another page upon click. The error message that keeps popping up is: Uncaught (in promise): Error: No component fac ...

Parse a string containing a selection of markdown by using regular expressions for tokenization

I need to tokenize a string using a regular expression that consists of markdown formatting. Specifically, bold text is denoted by **text** and italic text is denoted by _text_. To tokenize the string "a _b_ c **d** _e", it should be split into ['a & ...

How to manipulate local JSON files using AngularJS

I recently started learning angularjs and have been spending hours online trying to figure out how to access data from a local json file without the need for hosting it on localhost. Unfortunately, I haven't come across any solutions yet. I attempted ...

Incorporating an HTML page into a dialog using AngularJS: A step-by-step guide

Is it possible to dynamically change the content of a dialog by updating the URL? I have multiple HTML pages that I want to display in my dialog by simply changing the URL. <md-button ng-click="showDialog($event,'myurl/page-1.html')">Show ...