Anonymous function causing issue with Bootstrap collapse and hidden overlay functionality

Encountering a unique issue with Bootstrap 3 collapsible panels while designing a web page. The layout consists of images in one column and panels in another, where clicking on an image or panel link reveals a hidden overlay div with an updated iframe src attribute based on a custom tag. Strangely, when clicking on a panel link, the overlay briefly appears then disappears. Debugging efforts employed breakpoints in the code to find why the div is reverting to hidden status immediately. A workaround was discovered by avoiding anonymous jQuery functions and using explicit event handlers instead. Seeking insights into why the original approach failed.

Code snippet:

<div class="row" id="contentBlock">
<div class="col-md-offset-2 col-md-8">
    <div class="row">
        <div class="col-md-4">
            <div class="panel panel-default">
                <div class="survey-panel-heading">
                    <h4>Training Library</h4>
                </div>
                <div class="panel-body">
                    <p class="czsurvey-help-block" style="margin-bottom:10px;">Click on a category to see available training items</p>
                    <div class="panel-group" id="library">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                <h4 class="panel-title">
                                    <a data-toggle="collapse" data-parent="#library" href="#category1">
                                        Category #1
                                    </a>
                                </h4>
                            </div>
                            <div id="category1" class="panel-collapse collapse">
                                <div class="panel-body">
                                    <ul>
                                        <li><a onclick="return fireOverlay(this);" training-target="../resources/summary_2014_04_11_1397235407.pdf">Working Training 1</a></li>
                                        <li><a href="" class="trainingselector" training-target="../resources/summary_2014_04_11_1397235407.pdf">Not Working Training 1</a></li>                                                   
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="panel-group col-md-8">
            <div class="panel panel-default">
                <div class="survey-panel-heading">
                    <h4>Training Recommended for you</h4>
                </div>
                <div class="panel-body text-center">
                    <p class="czsurvey-help-block" style="margin-bottom:10px;">Click on a training item to view</p>
                    <div class="row">
                        <div class="col-md-3">
                            <img class="img-thumbnail trainingselector" src="../resources/Renders/SideViewReported.png" training-target="../resources/summary_2014_04_11_1397235407.pdf"/>
                            <h4>Training 1</h4>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="trainingoverlay">
    <div id="trainingcontent">
        <iframe id="contentdisplay" src="" frameborder="0" style="width:90%; height:88%;" scrolling="no"></iframe>
        <h4 style="color:White;">Was this training helpful? 
            <span style="color:White;">
                <input type="radio" id="A1" name=Q1 value="yes">Yes
                <input type="radio" id="A2" name=Q1 value="no">No
            </span>            
        </h4>
        <label class="btn btn-czbacknext" id="closebutton">
            Close Training
        </label>
    </div>
</div>

Javascript:

$(document).ready(function () {
$(".trainingselector").click(function () {
    $("#contentdisplay").attr("src", $(this).attr("training-target"));
    $("#trainingoverlay").show();
    $("#trainingcontent").show();
});
$("#closebutton").click(function () {
    $("#contentdisplay").attr("src", "");
    $("#trainingoverlay").hide();
    $("#trainingcontent").hide();
});
});

function fireOverlay(element) {
$("#contentdisplay").attr("src", $(element).attr("training-target"));
$("#trainingoverlay").show();
$("#trainingcontent").show();
}

Relevant CSS (how I hide the overlay...)

#trainingoverlay {
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
background-color: rgba(0,0,0,.55);
display: none;
z-index: 1;
}
#trainingcontent {
position: fixed;
width: 50%;
height:60%;
margin-left: 25%;
padding-top:2%;
top: 150px;
text-align: center;
display: none;
overflow: hidden;
z-index: 100;
background-color: rgba(0,0,0,.9);
}

Answer №1

The dilemma at hand is not about anonymous functions vs named functions. When you attach a handler directly to an a tag using onClick and then return false from it, you essentially prevent the default behavior of the click event. This means that clicking on a link will not perform its usual action of loading the link target. Since your fireOverlay function lacks a return statement, but you are using return fireOverlay() (which returns undefined since a function without a return statement defaults to undefined) in your onClick=, you are inhibiting the default event handling (you can achieve this by returning false or undefined from an onClick handler).

If jQuery is being utilized, the same principle applies - preventing the default behavior ensures that the browser does not navigate to the link.

Modify

$(".trainingselector").click(function () {
    $("#contentdisplay").attr("src", $(this).attr("training-target"));
    $("#trainingoverlay").show();
    $("#trainingcontent").show();
});

to

$(".trainingselector").click(function (event) {
    $("#contentdisplay").attr("src", $(this).attr("training-target"));
    $("#trainingoverlay").show();
    $("#trainingcontent").show();
    event.preventDefault();
});

This adjustment, as implied by its name, prevents the usual event handling so that the browser remains on the current page instead of following the link. In the updated version of your function, the event parameter captures the click event triggered by the link. By invoking preventDefault() on this event object, you halt the browser's standard procedure after executing your handler function.

By the way: The placement of preventDefault() within your handler function (whether at the beginning, end, or middle) does not affect its functionality, as long as it is called before the conclusion of the handler function.

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

Issue with JavaScript code for Google Maps API not functioning as expected

Can someone help me troubleshoot why my simple Google Maps setup isn't working? Thanks! HTML <script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBy2rXc1YewdnqhPaaEd7H0I4DTV_pc7fo&"> </script> <div id="map"> & ...

Identifying the parent div in jQuery based on a specific class condition

I have a few different posts that resemble the following ("example" being the post content): <div class="example"> <p><a href="">example</a></p> <span class="thumbs-rating-up thumbs-rating-voted" onclick="thumb ...

Toggle the row to expand or collapse upon clicking it

After extensive research, I have been unable to get the row expansion and collapse feature to work in my script. Here is my current script: <thead> <tr> <th width="5" class="cb"><input type="checkbox" id="cbcall" /& ...

Using Node.js to display the outcome of an SQL query

I have been attempting to execute a select query from the database and display the results. However, although I can see the result in the console, it does not appear on the index page as expected. Additionally, there seems to be an issue with the way the r ...

Include a Footer on the HTML Document

Having an issue with the placement of my footer in a web application. I've managed to generate XML data to render the HTML page and everything displays correctly except for the footer. The footer is supposed to be at the bottom of the page but it&apos ...

When attempting to access an API hosted on Cloudflare from Heroku, a 403 error is returned

I am currently utilizing the Cowin API () to access available slots. My implementation is based on Node.js. Interestingly, it functions well on my local machine but encounters an error after deployment on Heroku. 2021-05-09T11:07:00.862504+00:00 app[web.1] ...

Constructing an interactive table from a JSON dataset using Node.js and Express

Just starting out with Node.JS here! I'm currently working on creating a page with multiple tables and information using NodeJS. However, I've hit a roadblock when trying to display the result of an SQL query in an HTML table. Right now, I'm ...

What can I do to reduce the length of this code in JavaScript?

I'm trying to shorten my code by using arrays, but I'm having trouble getting it to work. Can someone help me out? // Task 1 var firstBox = document.getElementsByClassName('box1')[0] firstBox.addEventListener("mouseenter", function ...

The "placeholder" attribute effectively populates the form input in HTML, but when using Angular 2+, the "value" attribute does not fill the input field as expected

Within my Angular UI, I have implemented an edit button that allows users to transform a member's name heading into a form for editing and updating the name. The challenge lies in ensuring that the form is pre-filled with the current name. My issue a ...

What is the solution for untangling this complicated Javascript variable referencing issue?

Currently facing an issue that needs to be addressed: app.controller 'MainCtrl', ($scope, TestData) -> $scope.name = 'World' TestData.get(0).then (data)-> $scope.elem = data TestData.get(1).then (data)-> $scope ...

Verify if the header value corresponds

How can I validate the header value in a Node.js application? I want to restrict access to a certain route only if the user includes a specific header and its value matches what is expected. For instance, let's say the route requires a header like Acc ...

AngularJS retrieve data from JSON (like using MySQL)

My data is in JSON format: {"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","u ...

What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overl ...

The Bootstrap menu is having trouble collapsing properly

We're currently in the process of constructing a website using bootstrap, but we've encountered an issue with the menu bar. Upon visiting , you'll notice that the top menu functions properly and collapses perfectly when viewed on mobile dev ...

Tips for transferring input values between two PHP pages

I need to save various input values in a MySQL database, such as first name, last name, phone number, and mobile number. With a select query, I can retrieve all the entries from the database and display them on a single webpage. When a user clicks on a sp ...

Enable the button when there is an error after submission in AngularJS

Has anyone encountered issues with dynamically disabling a button? I noticed that my API delays for 2 seconds to mimic a slow connection. I expected the submit button to be disabled upon submission and then re-enable itself. In HTML, manually disabling t ...

Utilizing React Refs to Retrieve Value from HTML Select Element

I am currently working on a form that includes the use of an HTML select element. <select className="form-control" id="ntype" required > <option value = "">None</option> <option value = "1">1</option> < ...

What is the correct way to utilize the Vuex mutation payload object effectively?

I have two input fields where I can enter a value to search for either the name of a company or the location. The search functionality works when only one argument is provided in the foundJobs mutation and action. However, when the payload contains an obje ...

Tips for opening local HTML files on iPhones and Android devices

Is there a way to access local files on my PC from my iPhone and Android devices without having to upload them to an FTP server each time? I currently use Windows 7 with an iPhone 4 and an Android device. When I need to view a file on my iPhone's brow ...

Interested in learning how to code games using JavaScript?

Hi everyone, I'm currently exploring the world of Javascript and have been tasked with completing a game for a class project. The game involves a truck that must catch falling kiwis while only being able to move left or right. A timer is set for two m ...