There is no CSS styling present

I have a webpage where I want to display a modal overlay when a user clicks on an image or link. Initially, the modal is hidden and empty using this HTML:

<!--// MODAL: ITEM PROFILE //-->
<div id="profile" class="modal" style="visibility: hidden">
</div>
<!--// OVERLAY //-->
<div id="overlay" style="visibility: hidden"></div>

To trigger the modal when a user interacts with an image or link, I use this function:

function itemModal(id){
var modal = $("#profile");
if (modal == null){
    alert("Modal not found!");
}

if($(" #profile").style.visibility == "hidden"){
    $.ajax
      (
        { //Ajax call to get item data
          type: "POST",
          url: "/organizer/getItem",
          data: { item_id: id },
          dataType: "html",
          success: function( responseText, textStatus, XHR )
          {
            // select the element with the ID profile and insert the HTML
            $("#profile" ).html( responseText );
            $("#profile").style.visibility = "visible";
            $("#overlay").style.visibility = "visible"
          }
        }
      );
  }
  else{ //Modal is being displayed, hide it and remove contents
    $("#profile").html('');
    $("#profile").style.visibility = "hidden"; 
    $("#overlay").style.visibility = "hidden";
  }
}

However, when trying to trigger the modal, I encounter the error message

Uncaught TypeError: Cannot read property 'visibility' of undefined
. Upon further investigation, I discovered that even though the profile element exists, its style attribute is showing up as null, despite having inline CSS defined for it and additional styling in another file. What could be causing the style attribute to be null?

Answer №1

When working with jQuery objects, it's important to remember that they are actually arrays of DOM Objects, which have style properties.

You can achieve the desired effect by:

SET: $('#overlay').css('visibility', 'hidden')
GET: $('#overlay').css('visibility')

Alternatively, you can also use:

SET: $('#overlay')[0].style.visibility = 'hidden'
GET: $('#overlay')[0].style.visibility

Answer №2

When working with a returned jQuery object, make sure to use the css() method instead of using raw JavaScript Element properties. For example:

if($("#profile").css('visibility') == "hidden")

Answer №3

You seem to be confusing jQuery syntax with plain JavaScript.

Regular HTML elements have a style object, whereas elements wrapped in jQuery do not. If you are using jQuery, make sure to use

if ($(" #profile").css('visibility') == "hidden")

In addition, the line below will not function as expected.

if (modal == null){

This is because the value assigned to modal is still a jQuery-wrapped element. A jQuery object always has a 'truthy' value, even if it doesn't find any matching elements - which means it would never be null, false, or any other falsy value. Instead, try using:

if (modal.length){

...meaning "if the jQuery selector found any elements..."

Lastly, it's worth noting that what you're working with here isn't actually modal windows in the traditional sense. These are DHTML elements; true modal windows involve specific browser functionality where the user must interact before returning to the main application (such as an alert).

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

Internet Explorer 9 is implementing a conditional stylesheet designed for IE7

In order to address certain issues with older versions of Internet Explorer, I have included additional stylesheets as follows: <!--[if IE 8]> <link rel="stylesheet" href="/CallCentre/ServiceCloud/Content/IE8.css"> <![endif]--&g ...

Easier method for displaying array elements as list items in JavaScript

Working on exercises from a manual that required printing array items into list elements. Here is the code provided: <!doctype html> <html lang="en> <head> <title>Temperatures</title> <meta charset="utf-8"> &l ...

Encountering numerous TypeScript errors due to a JavaScript file in Visual Studio 2017

Kindly review the update below I utilized the following package as a foundation for my VS Project -> https://github.com/AngularClass/angular2-webpack-starter Everything ran smoothly in Visual Studio Code, but when I attempted to convert it into a Visu ...

What is the correct way to validate a form using input radio buttons?

I am experiencing an issue with validating the form using the validate() method. There seems to be a problem with this particular line of code: if(radios[i].value == "yes" && radios[i].checked == true) //DEBUG INFO: skips this step to else. It ap ...

lost websession while window.location.replace or href

I encountered an issue with losing the web session when trying to redirect from webform1 to webform2 using various methods, such as window.location.replace("webform2.aspx") and passing "/webform2.aspx" as a parameter. Despite my efforts, the session is los ...

Adjustable text size to accommodate different cultural changes

My team is working on an MVC web application, with CSS stylesheets utilized in views. We are trying to achieve the following scenario: Whenever the language culture changes from English to another language, we want the font size of a specific class to ...

Relocate the number of records displayed per page next to the pagination controls in datatables

Currently, I am utilizing datatables to create tables effectively using their provided example. However, I am encountering difficulty in moving the "records per page" element, which is contained within a "span6" class of bootstrap. I understand that this ...

Is it necessary to use `top` or `parent` when utilizing local scripts in an iFrame?

Is it possible to eliminate the use of top or parent in iFrame localized scripts, as the title suggests? Upon examining the screenshot below, I encounter a "not defined" error unless I include top or parent as a prefix to my function call. test(); does n ...

`Can you teach me how to dynamically load HTML elements using input JSON data?`

What is the best way to iterate through an input array of objects? I currently have data for only 2 people included. However, there are more than 50 people's information in the input and I need to loop through all of them. Here is a sample code snip ...

Implementing ui-router within the Ionic framework for AngularJS

I've been developing an app using the Ionic framework, which utilizes the ui-router. Currently, my app consists of just two simple pages but it's expected to grow in size. However, I'm encountering an error when transitioning from the first ...

Spin a three-dimensional cube on a platform using three.js with a unique functionality

I am attempting to create an animation featuring a cube on a flat surface. The cube can be rotated along the x/y axis only, with no need to show its underside. I want to be able to tip the cube over any edge - when a side of the cube touches the surface, i ...

Next.js getServerSideProps with axios (using withCredentials: true) does not include the HttpOnly cookie in the request

My current issue revolves around a dashboard page and a programs page. The complication arises on the programs page where server-side rendering (SSR) is causing trouble, as everything functions properly when my saga is called on the client-side from the da ...

What is the best way to ensure that the correct Url.Action is passed to a JQuery method without encountering any issues with extra amp

I'm attempting to initiate an ajax call in this manner: $('#Grid').load('@Url.Action("_AgentStatesGrid", "AgentStates", new { projectId = Model.SelectedProject, siteId = Model.SelectedSite })', null, refreshComplete); Regrettabl ...

PHP script that dynamically highlights text based on values retrieved from a database

I have multiple small HTML tables generated by PHP on a single page, each with a unique <table id="">. The data in these tables corresponds to entries in a MySQL table with matching IDs. What I am looking for is to automatically highlight the values ...

Retrieve Image/png using an Extjs ajax request

Hello, I am currently working on an application that is designed to showcase dynamically generated images stored on a server. The process involves fetching the image, typically in PNG format, using an Ajax Request. The data retrieved appears as follows: ...

What is the process for implementing Autocomplete in JsHelper?

Is it possible to create an Ajax Autocomplete using only pure JsHelper in JavaScript? Thank you, Celso ...

How can I create a three-column layout in CSS grid where there is one large column on the left and two smaller columns on the right?

https://i.sstatic.net/E1uQP.png Hi there! I'm currently working on replicating the image above using CSS grid and I've almost got it, but I'm facing an issue with the main content section that includes "Your Projects," "Announcements," and ...

JavaScript: Transforming a key-value pair collection into an array of objects

I'm looking to convert a dictionary into a list of dictionaries using JavaScript. Can someone help me with that? var dict = { "apple" : 10, "banana" : 20, "orange" : 30 } var data = [ {"apple" : 10}, {"ban ...

Issue TS8011 in Angular 6 is related to the restriction on using type arguments only in files with the .ts extension

I have a project in Angular 6 where I need to integrate a JS library. This library is confidential, so I can't disclose its details. The problem I'm facing is that the TypeScript compiler seems to misinterpret characters like <<24>>, ...

Creating pages or tabs within a table using HTML5 and Angular is a simple and effective way to organize

I have a REST response that returns around 500 records. These records are being displayed in an Angular table. I would like to add customization options for the user, allowing them to choose to display 10/20/30... records per page. Additionally, I want to ...