Simple steps to create a stylish modal popup using CSS and JavaScript

I recently created a simple code snippet to generate a modal highlight for an element.

card.click(function(){
    cloak.show();
    var cardClone = card.clone();
    cloak.append(cardClone);
    cardClone.css({
        position: 'absolute',
      top: card.offset().top - 7,
      left: card.offset().left - 7,
    }).addClass('selected');

var names = [
'arun',
  'ajesh',
  'amit'
];

var div = $('#card');
var cloak = $('#cloak');
var sel;

$.each(names, function(i, obj){
var card = $('<div/>').addClass('spacetype').html(obj);
  div.append(card);
  card.click(function(){
  cloak.show();
    var cardClone = card.clone();
    cloak.append(cardClone);
    cardClone.css({
    position: 'absolute',
      top: card.offset().top - 7,
      left: card.offset().left - 7,
    }).addClass('selected');
  });
});

cloak.click(function(){
cloak.hide();
  cloak.empty();
})
body {
  background-image: url('http://placekitten.com/1024/678')
}
.spacetype {
  display: inline-block;
  height: 100px;
  width: 75px;
  border: 1px solid black;
  padding: 10px;
  background-color: rgba(244,250,54, .6);
  margin: 5px;
  font-weight: bold;
  border-radius: 7px;
  font-family: Arial;
}

.selected {
  border: 3px solid yellow;
  z-index: 10;
}

#cloak {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background-color: rgba(0,0,0, 0.3);
  display: none;
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="card">
  
</div>
<div id="cloak"></div>

The approach is straightforward.

  1. Create a basic modal structure (a div with absolute positioning and alpha transparency).
  2. Duplicate the chosen box.
  3. Position the duplicate precisely based on the original box's offset.

Is there a CSS-only method to achieve this effect without cloning the DOM element?

Fiddle: https://jsfiddle.net/9ew7aq4v/

Answer №1

From my understanding, there isn't a CSS-only solution for this task - utilizing JavaScript to handle click-events is necessary. However, there is a simpler approach available to address your issue without needing to clone the object (assuming that's your goal).

One option is to utilize the z-index property to elevate the card above the overlay. It's important to note that you must specify a position for z-index to take effect. Check out the updated fiddle: https://jsfiddle.net/9ew7aq4v/1/

Answer №2

If you're looking to add a touch of creativity to your website, you can experiment with some pure HTML/CSS techniques just for fun:

body {
    background-image: url('http://placekitten.com/1024/678');
}
.spacetype {
    display: inline-block;
    position: relative;
    height: 100px;
    width: 75px;
    border: 1px solid black;
    padding: 10px;
    background-color: rgba(244, 250, 54, 0.6);
    margin: 5px;
    font-weight: bold;
    border-radius: 7px;
    font-family: Arial;
}

.spacetype:focus {
    outline: 0;
    z-index: 10;
    background-color: rgba(244, 250, 54, 0.8);
}

.spacetype:focus:after {
    position: absolute;
    content: '';
    top: -1px;
    right: -1px;
    bottom: -1px;
    left: -1px;
    border: 3px solid yellow;
    border-radius: 7px;
}

.spacetype:focus ~ #cloak {
    position: absolute;
    display: block;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    background-color: rgba(0,0,0, 0.3);
    padding: 0;
    z-index: 0;
    pointer-events: none;
}
<div tabindex="1" class="spacetype">arun</div>
<div tabindex="2" class="spacetype">ajesh</div>
<div tabindex="3" class="spacetype">amit</div>
<div id="cloak"></div>

Check out the code on JSFiddle

Although using Javascript may provide more flexibility and scalability, exploring unique HTML/CSS solutions can be a fun way to enhance your website.

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

Creating a custom jQuery selector

I've been struggling with a particular problem all day today, trying different approaches but still unable to find a solution. The crux of the issue is this: I have multiple JavaScript functions running to determine whether certain variables should b ...

Error encountered with Protractor: 'TypeError: undefined is not a function'

I have explored various discussions on this particular error code. Nevertheless, I am finding it challenging to come across any solutions that are effective (or perhaps I am just not understanding them). While constructing a Protractor test for a webpage, ...

Upgrading to React Router v6: Implementing Loader Functions with Context API

Having issues implementing loaders in React-Router V6 while making a request for a page through a function located in the context file. Unfortunately, I can't access the context from main.js where the router is defined. Main.js import ReactDOM from & ...

Reference now inactive in an array object no longer exhibiting reactivity

After implementing the following code successfully, we noticed that changing the language updates the text correctly thanks to the ref: const mainNavigationLinks = computed(() => [ { label: context.root.$t('navigationMenu.home') }, { labe ...

Currently in the process of developing an electron application, I encountered an Uncaught Exception error stating: "TypeError: $.ajax is not

I'm currently working on an electron app that interacts with an API endpoint and displays the response on the page. Due to electron's separation of main process and renderer process, I'm using a preload script to facilitate communication bet ...

Extract the "_id" value from the array in the v-for loop and then store and reuse it in the data object // using vue-cli

Currently, I am iterating through [postArray] to retrieve various posts, each of which has its own unique "_id". My goal is to utilize this "_id" to add likes to the corresponding post. This is the v-for loop I am using: <div class="posts" v- ...

The Laravel view is displaying on Chrome dev-tools instead of redirecting to the blade template

Hello amazing developers at stackoverflow, I'm currently working on a project focused on campaign management. The goal is to enable users to create, edit, and preview their campaigns before publishing them. To achieve this, I am utilizing MySQL and F ...

Django auto-fill using the primary key on the page

Is there a way to automatically select the id or (pk) of an employee's page when adding documents to their profile through a form? Any suggestions for a solution would be greatly appreciated! view.py def createDocument(request): forms = documentF ...

"Even as the page scrolls down, the scrollbars stubbornly stay anchored at the

I'm currently working on a webpage that includes a link to an anchor, which should be a straightforward case. The link code looks something like this: <a href="#target">Link</a> And the anchor code looks like this: <a name=" ...

Automatically submitting a form in the absence of the user from the page

Is it possible to automatically submit a form when the user exits the page? Here's the code snippet: <form class="carform" method="get"> <input type="hidden" name="number_plate" value="{{ car.number_plate }}"> </form> I want the ...

Is there a way to invoke bootstrap 5 modals using JavaScript without the need for jQuery in the scripts?

Despite the existence of similar inquiries regarding this issue, I am determined to discover a solution that does not involve integrating jQuery into my scripts. Currently, I am encountering an error when attempting to invoke bootstrap 5 modals using JS. M ...

Ways to update a row in ui-grid?

I am attempting to refresh only the specific row that has been edited in the ui-grid without refreshing the entire table. My scenario involves editing a row in the grid, triggering a rest call, and then updating only that particular row in the grid. Upon ...

How can I create a new div element for every item in an array by utilizing JSX?

I am currently working on creating a div element for each item in an array using reactjs JSX. I wasn't sure how to tackle this, so I attempted the following approach: {results.map((element, index) => ( <div key={index} className={ ...

Traversing an array of objects can result in an extraneous comma being displayed in the markup

View screenshot showing unwanted comma in output Hello there, I'm currently working on a gold shop website and dealing with an array of product objects. When mapping through this array to display products on the main page, I've encountered an is ...

Sending data from an HTML table hyperlink to a SQL query on a subsequent page

I am in need of assistance with passing a value from a database. I have successfully achieved this using drop-down boxes, selecting the option and then posting it with a submit button to populate tables in Display.php. However, my current task involves an ...

modifying the placeholder font and relocating chips/tags beneath the search bar

I'm encountering some challenges with material-ui that I could use assistance with. Firstly, is there a method to have the tags/chips displayed below the search bar instead of above it? Additionally, I've been attempting to italicize and adjust ...

Error occurred in AngularJS when trying to pass a parameter from an HTML page in order to retrieve data using

I am encountering an issue when attempting to pass a parameter from the HTML page to delete a row from the database. The http.get() method retrieves data for all books, and I am passing the ID for a specific book for deletion. However, I am facing a syntax ...

A tutorial on how to showcase choices in a collection_select using the Rails controller

When a user selects a specific designation, the corresponding benefits should be loaded in a dropdown menu. I have implemented this functionality using an ajax call. HTML: <label>Designations</label> <%= f.association :designation, input_h ...

The TipTap Editor does not properly register spaces

In our project, we are utilizing the TipTap rich text editor. However, we are encountering an issue where spaces are not being recognized correctly - a space is only created after every 2 clicks. Our framework of choice is Vue.JS. import { Editor, EditorC ...

When a required field is empty or an alert modal for incorrect input appears, the login inside the dropdown will automatically close

Currently, I am facing an issue with a login form enclosed within a Bootstrap 4 dropdown. Whenever I click on the dropdown, it pops up as expected. The problem arises when a field in the form is required and there is no message displayed upon closure (HTM ...