ThatsNotMyName ThatsNotMyName - 8 months ago 32
Javascript Question

Disable lightbox with javascript

I have an image that when clicked, will open up in a lightbox (script from and what I want to do is disable that from happening when a button is switched to off. (So clicking the image does nothing.)

I've tried to use .off and .unbind following some other answers on the site to disable the lightbox but none of them are working for me.
I have also followed How do I dynamically enable/disable links with jQuery? as suggested but have had no luck.

Below is the HTML.

<div style="margin-left:10%;padding:1px 16px;">
<section id="four_columns">
<article class="img-item">
<a href="img/livingroom.jpg" data-lightbox="livingroom"><img id="img_window1" src="img/livingroom.jpg" width="200" height="120"></a>
<strong>Living Room
<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="window1" value="window1" checked>
<label class="onoffswitch-label" for="window1">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>

and javascript

<script type="text/javascript">
$(document).ready(function() {
var full_opacity = 1;
var faded_opacity = 0.3;
var fade_speed = 'fast';
var objid;

$('input[name="onoffswitch"]').each(function() {
objid = "#img_" + $(this).val();

if($(this).prop('checked')) {
$(objid).css('opacity', full_opacity);
else {
$(objid).css('opacity', faded_opacity);

$('input[name="onoffswitch"]').change(function() {
var objid = "#img_" + $(this).val();
if($(this).prop('checked')) {
$(objid).fadeTo(fade_speed, full_opacity);
else {
$(objid).fadeTo(fade_speed, faded_opacity);
$(objid).parent().unbind('click'); /* Here is where I want to implement the code. */

Any help would be appreciated.


You need to disable both the lightbox (by removing the data-lightbox attribute it looks for) and the default functionality of the underlying hyperlink.

$lightboxes = $(".myImageLinks");    

// save the old data attributes in an array, then remove them
var lightboxData = $ {
    return $(this).data("lightbox");

// prevent the browser from traveling to the link target
var preventer = function(e) { 

to disable the link, and

$(objid).parent().unbind('click', preventer);
$lightboxes.attr("data-lightbox", function(i, old) {
    return lightboxData[i];

to re-enable the default click functionality. (Another option for disabling the lightbox would be to just remove the "data-lightbox" attribute and save it temporarily as an "data-oldlightbox" attribute instead.)

I feel that the library should have used a class to identify which elements are eligible for lightboxing. That's important to the user, not just the library, and should be marked up semantically. Data attributes are not for CSS hooks.