The CSS styling for an anchor link that is supposed to dynamically load an element from a file using jQuery is not

I am facing an issue where I need to display only a specified anchored div and be able to share the link with that anchor. However, the functionality is not working as intended. When attempting to load the bar1 (blank) or bar2 (blank) link from the main.html page, which contains anchors bar1 or bar2 (www.foo.bar/main.html#bar1), there are problems with handling the CSS and jQuery if loaded from a file. Interestingly, when the #foo element is dynamically appended as an HTML string, the anchored link seems to work fine (e.g. www.foo.bar/main.html#foo). Clicking on the links such as foo (blank), bar1 (blank), bar1, bar2 (blank), and bar2 reveals that bar1 (blank) and bar2 (blank) fail to show the respective bar1 or bar2 div. This behavior seems to be related to asynchronous file loading. Is there a solution to overcome this challenge?

Main Content in main.html:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
        <script>
$("<div>").load("bar1.html #bar1", function() {
  $('body').append($(this).html());
});
$("<div>").load("bar2.html #bar2", function() {
  $('body').append($(this).html());
});

$(function() {
    $( 'body' ).append("<div id='foo' style='background-color:#8F8;'>FOO</div>");   
});
        </script>   
        <style>
div:not(:target) { display: none; }
div:target { display: block; }  
        </style>    
    </head>
    <body>
        <a href="main.html#foo" target="_blank">foo (blank)</a>
        <a href="main.html#bar1" target="_blank">bar1 (blank)</a>
        <a href="main.html#bar1">bar1</a>
        <a href="main.html#bar2" target="_blank">bar2 (blank)</a>
        <a href="main.html#bar2">bar2</a>
    </body>
</html>

Contents of bar1.html:

<div id='bar1'>BAR1</div>

Contents of bar2.html:

<div id='bar2'>BAR2</div>

Answer №1

Uncertain of your exact intention.

Consider encapsulating your jQuery within a document ready function.

<script>
  $(document).ready(function(){

    $("<div>").load("bar.html #bar", function() {
      $('body').append($(this).html());
    });

    $( 'body' ).append("<div id='foo' style='background-color:#8F8;'>FOO</div>");  

  }); 
</script>   

Answer №2

Here is an example of how you can set up main.html

<html>
    <head>
        <style>
        div{
            display: none;
        }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $("<div>").load("bar.html #bar", function() {
                  $('body').append($(this)[0].innerHTML);
                });
                var hash = window.location.hash;
                $('a').on('click', function(){
                    if(!hash && !($(this).attr('target'))){
                        $('[id="'+$(this).attr('href').substring(1)+'"]').show('slow');
                    }
                });
                setTimeout(function(){
                    $('[id="'+hash.substring(1)+'"]').show('slow');
                 }, 100);
                $('body').append("<div id='foo' style='background-color:#8F8;'>FOO</div>");
            });
        </script>       
    </head>
    <body>
        <a href="#foo" target="_blank">foo (blank)</a>
        <a href="#bar" target="_blank">bar (blank)</a>
        <a href="#bar">bar</a>
    </body>
</html>

bar.html remains unchanged

Answer №3

Implemented a file counter along with a function to decrease the counter and reset the anchor tag.

index.html

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
        <script>
var count = 3;

function onUpdateData() {
    if (--count <= 0) {
        var hash_value = window.location.hash;
        window.location.hash = '';
        window.location.hash = hash_value;
    }
}

$.get('data1.html', function (info) {
    $('body').append(info);
    onUpdateData();
});
$.get('data2.html', function (info) {
    $('body').append(info);
    onUpdateData();
});

$(function() {
    $( 'body' ).append("<div id='foo' style='background-color:#8F8;'>FOO</div>");  
});
        </script>   
        <style>
div:not(:target) { display: none; }
div:target { display: block; }  
        </style>    
    </head>
    <body>
        <a href="index.html#foo" target="_blank">foo (blank)</a>
        <a href="index.html#data1" target="_blank">data1 (blank)</a>
        <a href="index.html#data1">data1</a>
        <a href="index.html#data2" target="_blank">data2 (blank)</a>
        <a href="index.html#data2">data2</a>
    </body>
</html>

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

Encountering errors when initializing a JavaScript module through Angular2 instantiation

I have a situation where I need to utilize a plain JavaScript module within my Angular service. However, when I try to create an instance of the module in the constructor, I encounter the following error: TypeError: Engine is not a constructor The code ...

Tips for displaying an edit icon on an individual row item when it is hovered

Attempting to create a functionality where hovering over a row in React triggers the appearance of an edit button/icon next to the folder name. The current approach involves assigning individual states to each row and utilizing a key to track them separate ...

Experience a seamless front/back DIV transition with a mouseover effect similar to the ones on USAT

Recently, I was tasked with creating a mouseover transition effect for a div similar to the one used on USAToday's website. The structure of the boxes on the site includes: <div class="asset"> <div class="front">'image and some t ...

Is there a way to enclose individual text nodes that are divided by <br><Br> within their own set of <p> tags

Received content from a webservice that I can't modify includes: <div id="entrance" style=""> Habilitação / Diploma de Ensino Medio Diploma de Ensino Pre Universitario <br> <br> Diploma Record of study </div&g ...

The toggle feature in jQuery doesn't hide content in the same manner as it was originally shown

Just diving into the world of jquery and I'm experimenting with the toggle function to display and hide a div, along with adding or removing an active class. http://jsfiddle.net/MAkyw/ I've encountered 2 issues: 1) The 'active' class ...

Tips for CSS and jQuery: Show link when hovered over and switch the visibility of a content div

I'm facing an issue with a link in the horizontal navigation bar. When a user hovers over it, I want another div to slide down just below it. The problem is that using the .toggle method doesn't work as expected. It continuously toggles the div e ...

Learn how to redirect email recipients to a separate page when they click on the email subject line

Currently, I am working on developing an inbox feature in PHP where it shows the Mail Id and Subject. When a user clicks on a specific division containing the mail id and subject, it should navigate to a new page in PHP that displays the body and attachmen ...

Cancel event for file uploads in Angular on Internet Explorer 11

We are currently facing an issue with file upload functionality in Internet Explorer 11 while using Angular 11. The problem lies specifically with the Cancel button of the file dialog box. <input #fileUploadCtrl class="form-control" type=" ...

What is the best method for organizing data in rows and columns?

I attempted to use my map function to iterate over the data and display it, but I struggled to format it into rows and columns. The requirement is for 5 fixed columns with dynamically changing rows, making array indexing impractical. Here is the code snip ...

Ways to modify div content depending on the size of the screen

When the screen size becomes small, my goal is to modify the content within the row divs of the indices_container. Currently, all screen sizes display the index name, price, 1-day change, and year-to-date (YTD) change for each row. I only want to show the ...

Trouble with the display of selectable options

On my webpage, I have implemented two select elements that are dynamically populated on the server side. The first select, known as the "master" select, acts as a filter for the second select by hiding certain options using the hidden attribute. For examp ...

AngularJS Error: Attempting to Access Undefined Object - Jasmine Testing

Encountering an error while running Jasmine tests when trying to mock/spy on an API call in the tests. Below is the code snippet responsible for calling the API: UploadedReleasesController.$inject = ['$log', '$scope', '$filter&apo ...

javascript tutorial on how to insert user-generated objects into an array of objects

I'm struggling to figure out how to create an object that will be made from user input and then added to an array of objects. Here is what I've attempted: let NewContact = { firstName: "first name", lastName: "last name&qu ...

The Uniqueness of JavaScript's Special Characters in Regular

In the given code snippet, a method is provided to highlight substrings within a large string. However, there seems to be an issue with supporting a special character * which should represent any string of any length. Ideally, inputting * in the search t ...

Using Reactjs to create a custom content scroller in jQuery with a Reactjs twist

I am attempting to implement the Jquery custom scrollbar plugin here in my React project. Below is a snippet of my code: import $ from "jquery"; import mCustomScrollbar from 'malihu-custom-scrollbar-plugin'; ..... componentDidMount: function() ...

Make sure to allow the async task to complete before beginning with Angular JS

As I develop an app using MobileFirst v8 and Ionic v1.3.1, I encounter issues with timing in my code execution. Specifically, when the application initiates, the regular ionic angular code within my app.js file runs. This section of the code handles the i ...

Unable to attach scope variables in AngularJS

I currently possess the following files: index.html: <!DOCTYPE html> <html> <head> <title>Gestore Anagrafica</title> </head> <body> <div> <h3>Insert new person</h3> <d ...

Using Jquery's $.each() method within an ajax call can be a powerful

Is it possible for a jQuery each loop to wait for Ajax success before continuing when sending SMS to recipients from an object? I want my script to effectively send one SMS, display a success message on the DOM, and then proceed with the next recipient. O ...

What is the best method to eliminate elements from a queue using JavaScript?

I recently attempted to incorporate a queue feature into my JavaScript code. I found some helpful information on this website. While I successfully managed to add items to the queue, I faced difficulties when attempting to remove items from it. var queue ...

What are some methods for saving HTML form data locally?

Creating an HTML form and seeking a solution for retaining user data even after closing and reopening the window/tab. Utilizing JavaScript cookies or HTML 5 local storage would require writing code for every input tag, which could be time-consuming especi ...