Using JavaScript to bind a function call to a specific ID

Within an onclick event in an image, I have a function that I want to use to bind the same function to another div. No jQuery is used.

<img id="img1" onclick="toggle(this)" src="https://images.duckduckgo.com/iu/?u=http%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.Mde7815d5c3b846360c29e9aa3ea9a10fH0%26pid%3D15.1&f=1" alt="Image" style="width:128px; height:auto; cursor:pointer; z-index:0;"/>
  <p>
    Test text
  </p>
  <p>
    Test text 2
  </p>
  <script type="text/javascript">
    function toggle(doc){
      var mask = document.getElementById('overlay');
      var io = doc.tog ^= 1;
      doc.width_org = io ? doc.style.width : doc.width_org;
      mask.style.visibility = io ? "visible" : "hidden";
      doc.style.zIndex = io ? 2 : 0;
      doc.style.width = io ? (doc.naturalWidth + "px") : doc.width_org;
      doc.style.align = io ? "center" : "left";
      doc.style.vAlign = io ? "middle" : "top";
      doc.style.position = io ? "fixed" : "relative";
      doc.style.top = io ? "50%" : "0px";
      doc.style.left = io ? "50%" : "0px";
      doc.style.marginTop = io ? "-" + (doc.naturalHeight / 2) + "px" : "0px";
      doc.style.marginLeft = io ? "-" + (doc.naturalWidth / 2) + "px" : "0px";
    }
  </script>
  <div id="overlay" style="position:fixed; top:0px; left:0px; width:100%; height:100%; background:#000000; opacity:0.8; z-index:1; visibility:hidden"></div>

I aim to attach a callback to the toggle function for the ID overlay, passing back doc data. So, when clicking the img, its gallery effect toggles, and clicking the overlay div should also close it similar to clicking the img itself.

Answer №1

To ensure the toggle function works properly, simply add a single line to the end of toggle. This line will call toggle for the currently opened image onclick of the div, and then clear the onclick event. Here is how you can implement this:

document.getElementById('overlay').onclick = function () { 
    toggle(doc); 
    this.onclick = null; 
};

If you want to see it in action, here's a code snippet for you to run:

<img id="img1" onclick="toggle(this)" src="https://images.duckduckgo.com/iu/?u=http%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.Mde7815d5c3b846360c29e9aa3ea9a10fH0%26pid%3D15.1&f=1" alt="Image" style="width:128px; height:auto; cursor:pointer; z-index:0;"/>
  <p>
    Test text
  </p>
  <p>
    Test text 2
  </p>
  <script type="text/javascript">
    function toggle(doc){
      var mask = document.getElementById('overlay');
      var io = doc.tog ^= 1;
      doc.width_org = io ? doc.style.width : doc.width_org;
      mask.style.visibility = io ? "visible" : "hidden";
      doc.style.zIndex = io ? 2 : 0;
      doc.style.width = io ? (doc.naturalWidth + "px") : doc.width_org;
      doc.style.align = io ? "center" : "left";
      doc.style.vAlign = io ? "middle" : "top";
      doc.style.position = io ? "fixed" : "relative";
      doc.style.top = io ? "50%" : "0px";
      doc.style.left = io ? "50%" : "0px";
      doc.style.marginTop = io ? "-" + (doc.naturalHeight / 2) + "px" : "0px";
      doc.style.marginLeft = io ? "-" + (doc.naturalWidth / 2) + "px" : "0px";
      document.getElementById('overlay').onclick = function () { toggle(doc); this.onclick = null; };
    }
  </script>
  <div id="overlay" style="position:fixed; top:0px; left:0px; width:100%; height:100%; background:#000000; opacity:0.8; z-index:1; visibility:hidden"></div>

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

Set the background to be transparent while keeping the text opaque

Is there a way to make only my div transparent using the opacity property while keeping the font normal? I cannot assign a separate class or id to the content as it is dynamically generated. Also, using background: rgba(); is not an option for me. {opacit ...

Navigation bar options across various web pages

In my Next JS project, I encountered an issue with the Navbar component. By default, the Navbar elements change color from white to black when scrolling below 950px. However, I needed to make an exception for another specific page ("/lodge/page.tsx"). On t ...

Optimizing the loading of flash objects to improve website

I have successfully implemented the jQuery lazy-loading plugin to defer loading of images below the fold on a large web page. This method works well for images, but now I am looking to apply the same technique to a large Flash object that is also positione ...

How can I employ Single Sign-On (SSO) for my-website's account across various websites?

I'm looking to create a gaming platform similar to Epic Games, which we'll call "AB." I'd like game developers to be able to connect their games with my website and offer a "Login With AB" option on their login pages. Is this feasible? Thank ...

Surprising invocation of method or property access detected on IE8 within jQuery

I encountered an issue on my website: Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0) Timestamp: Fri, 27 Jul 2012 08:54:50 UTC Message: An unexpected method or property access call has occurred. Line: 5 ...

Unlimited Scrolling in Angular 2: A Complete Guide

For my current project, I am utilizing angular2-infinite-scroll. My concept is to load 6 items on the initial page load and then add an additional 6 items each time the user scrolls to the bottom of the page. However, I have encountered an issue where the ...

Buttons and links with intricate geometries

I am currently developing a web application using Java/JSF and I am interested in finding out about technologies that would allow me to define intricate shapes as clickable buttons or links. Right now, my only option is to split an image into smaller trans ...

Create a dynamic jQuery gallery with generated content

Currently I am working on a personal project and facing challenges in creating the correct markup using jQuery. I have an operation that provides a list of images to be displayed in this JSON format: [{ "Id": imageid, "imagePath": path to image, ...

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...

PhoneGap and jQuery prove ineffective in fetching json results from Twitter

I've been working on a project to fetch the most recent 50 tweets with a specific hash tag. The project is built for mobile devices using PhoneGap (0.9.6) and jQuery (1.6.1). Below is my code: function retrieveTweets(hash, numOfResults) { var uri ...

Request for a new login using credentials via ajax

We've set up a web application on a LAMP(PHP) system that makes around 40 Ajax calls. Users are tracked using PHPSessions with a 1 hour cookie lifespan (which we want to maintain for quick expiration). ISSUE: If a user is inactive for the full hour an ...

JQuery triggers form submission after multiple clicks - Validation needed

I'm having trouble understanding why the validation is not working on the first click but works later on. I've added the validate plugin to my JS file so that the form is validated after being clicked. The validator is set when the document is ...

Aligning text vertically in a dropdown menu using HTML and CSS

I am currently in the process of enhancing my website with drop-down menus, specifically from the gray buttons located at the top of the page. Using HTML and CSS lists (code provided below), I have successfully implemented the functionality. However, I am ...

Is it recommended to incorporate router.isReady when making requests with react-query?

Struggling with incorporating react-query into my codebase, currently using getStaticProps. Experimenting with router.isReady from next/router to ensure the page waits for router.query value before passing it as props to the react hook. Take a look at my ...

HTML5Up! Skyrocketing with Meteor showers

While attempting to utilize a responsive site template from , I encountered several issues. To test the template, I downloaded the Striped package and created a clients folder in a Meteorite app where I placed the Striped folder. In order to make it work, ...

What are the steps to integrate TypeScript into JavaScript code?

How can I import a TypeScript class in a Node CommonJS JavaScript file? When using mongoose in my TypeScript code, I typically do the following: // user.model.ts export const UserModel = model<User>('User', schema); In my JavaScript code: ...

How can I transform a mat-list into a dropdown menu in Angular?

I recently used Angular to create a list using mat-list. Here is the code I implemented: <mat-list style="display: inline-grid;"> <mat-list-item *ngFor="let item of item"> <mat-checkbox [(ngModel)] ...

"Stuck: CSS Div Transition Effect Refuses to Cooper

I am looking to incorporate a transition on my div when it is clicked. I've tried using jQuery with this example: http://jsfiddle.net/nKtC6/698/, but it seems to not be working as expected. So, I want to explore another example using CSS: http://jsfid ...

Verifying conditions in an AJAX-based upload system using JavaScript

Recently, I was working on implementing a JavaScript/AJAX upload system with a progress indicator based on a tutorial. The process went smoothly, and I even managed to include a CSS progress bar for visual representation. However, I encountered a hurdle th ...

Issue with Text not Showing in Bootstrap Carousel Example

Hey everyone! I'm currently experimenting with some bootstrap features and encountering some difficulties with the carousel element. I'm attempting to implement this example -> https://getbootstrap.com/docs/4.5/examples/carousel/ The problem ...