How to use the esc key to close lightbox page overlay - lightbox

I have a question about a lightbox see my jsFiddle.
Clicking on one of the images opens a bigger version of the painting as a page overlay.
How to use the ESC key to close this page overlay?
And how to use the arrow keys to move to the next image?
What kind of jQuery plugin / javascript would I need to make this happen?
<ul class="lb-album">
<li>
<a href="#Fly-My-Pretties-Walled-Garden">
<img src="http://sandipa.com.au/images/works-for-sale/thumbs/Fly-my-Pretties-Walled-Garden-sm.jpg" alt="Fly My Pretties: Walled Garden">
<span>Fly My Pretties</span> </a>
<div class="lb-overlay" id="Fly-My-Pretties-Walled-Garden">
x Close
<img src="http://sandipa.com.au/images/2010-2011/1000px-wide/Fly-my-Pretties-Walled-Garden.jpg" alt="Fly My Pretties: Walled Garden">
<div>
<h3>Fly My Pretties: Walled Garden<span>mixed media on canvas</span></h3>
<p>72 x 137 cm</p>
Prev
Next
</div>
</div>
</li>
<li>
<a href="#Central-Highlands-Circle-of-Gold">
<img src="http://sandipa.com.au/images/works-for-sale/thumbs/Central-Highlands-Circle-of-Gold-sm.jpg" alt="Central Highlands: Circle of Gold">
<span>Circle of Gold</span> </a>
<div class="lb-overlay" id="Central-Highlands-Circle-of-Gold">
x Close
<img src="http://sandipa.com.au/images/works-for-sale/Central-Highlands-Circle-of-Gold.jpg" alt="Central Highlands: Circle of Gold">
<div>
<h3>Central Highlands: Circle of Gold<span>mixed media on canvas</span></h3>
<p>51 x 108 cm</p>
Prev
Next
</div>
</div>
</li>
</ul>

A full implementation of Pure Javascript Lightbox or Image Popup Modal is available in one my Answers at https://stackoverflow.com/a/67169851/8210884.
This Answer mentioned in the link above allows handling both the issues of Hiding Lightbox with ESC key as well as navigating through images in Lightbox using Left and Right arrow key.
Here are the Pieces of code from that Answer which will help us achieve these Two issues.
Hiding the Lightbox with ESC key :
if(event.keyCode==27){ // If ESC key is pressed
if(document.getElementById("lightbox-container").classList.contains("showcontainer")){ // LIGHTBOX ON
document.getElementById("lightbox-container").classList.remove("showcontainer");
}
}
Navigating through all the images on a Webpage in Lightbox with Left and Right Arrow key :
else if(event.keyCode==37) { // Left arrow key
if(document.getElementById("lightbox-container").classList.contains("showcontainer")){ // LIGHTBOX ON
// first get the URL of image displayed in the LIGHT BOX
var currimgsrc = document.getElementById("lightbox-cont-img").getAttribute("src");
// now match the sequence number in the array
var serialofarray = 0;
for(k=0;k<allimgurlarray.length;k++){
if(currimgsrc == allimgurlarray[k][2]){
serialofarray = allimgurlarray[k][0];
}
}
// with LEFT arrow, we are supposed to reduce the sequence and then use its ATTR SRC to LIGHT BOX
if(serialofarray<=0){
serialofarray = allimgurlarray.length - 1;
}
else {
serialofarray = serialofarray - 1;
}
console.log("Left Arrow : "+serialofarray);
document.getElementById("lightbox-cont-img").setAttribute("src", allimgurlarray[serialofarray][2]);
}
}
else if(event.keyCode==39) { // Right Arrow Key
if(document.getElementById("lightbox-container").classList.contains("showcontainer")){
// first get the URL of image displayed in the LIGHT BOX
var currimgsrc = document.getElementById("lightbox-cont-img").getAttribute("src");
// now match the sequence number in the array
var serialofarray = 0;
for(l=0;l<allimgurlarray.length;l++){
if(currimgsrc == allimgurlarray[l][2]){
serialofarray = allimgurlarray[l][0];
}
}
// with RIGHT arrow, we are supposed to increase the sequence and then use its ATTR SRC to LIGHT BOX
if(serialofarray>=allimgurlarray.length-1){
serialofarray = 0;
}
else {
serialofarray = serialofarray + 1;
}
console.log("Right Arrow : "+serialofarray);
document.getElementById("lightbox-cont-img").setAttribute("src", allimgurlarray[serialofarray][2]);
}
}
These conditional cases related to Key Pressing events are tackled in document.onkeydown = function(event).
This piece of code below is very important for disabling the default behaviours of Key pressing events on IMG tags as well as stacking up all the images on a webpage in an Array to allow Navigation in Lightbox with Left and Right arrow key.
// Select all A tags with IMG child nodes
var atagswithimgtag = document.querySelectorAll("a[href]");
// then prevent the default behaviour of A tags by preventing of opening new page by HREF
// as well as collect all the HREF of A tags with images to enable RIGHT and LEFT arrow key
var allimgurlarray = [];
for(i=0;i<atagswithimgtag.length;i++){
var childAIMGtag = atagswithimgtag[i].childNodes;
if (childAIMGtag[0].nodeType != Node.TEXT_NODE) // or if (el[i].nodeType != 3)
{
// this seems too be a A tag with IMG tag as Childnode
// first we need to prevent the default behaviour of opening the IMG in New Tab
atagswithimgtag[i].addEventListener("click", function(event){
event.preventDefault();
});
// second is when we need to fill image URL aray with A HREF
var listofnodes = atagswithimgtag[i];
allimgurlarray[i] = [];
allimgurlarray[i][0] = i;
allimgurlarray[i][1] = " Image URL is ";//listofnodes.getAttributeNode("title").value;
allimgurlarray[i][2] = listofnodes.getAttributeNode("href").value;
}
console.log(childAIMGtag[0].innerHTML);
}

Related

Animate row background with css when data has changed

I am using Telerik Grid for Blazor WASM.
When data has changed on the server. I get notified via a SignalR connection.
I would like the affected rows to change background color and then return to the normal background color.
Could be a transition to red and fade back to the white or gray color.
I have seen many examples using hover and transitions. But this should be shown without user interaction and preferably delayed on items not in the current view. So when you scroll the grid and the items become visible, the animation starts.
Can AOS https://github.com/michalsnik/aos be used? Or will it only trigger on scroll?
The easiest way for me would be to set a class on the row in the row render event. But it’s a razor page so I can code a custom template.
Whatever can be done using :hover can be done if you add a class (then remove it after the transition). As for the appear only after scroll, you can check for the element is in view using the provided function.
function isScrolledIntoView(el) {
// from https://stackoverflow.com/a/22480938/3807365
var rect = el.getBoundingClientRect();
var elemTop = rect.top;
var elemBottom = rect.bottom;
// Only completely visible elements return true:
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
// Partially visible elements return true:
// isVisible = elemTop < window.innerHeight && elemBottom >= 0;
return isVisible;
}
var el = document.querySelector(".row")
window.addEventListener("scroll", function() {
if (isScrolledIntoView(el)) {
if (el.getAttribute("data-did-it")) {
return;
}
el.setAttribute("data-did-it", "true")
el.classList.add("active")
setTimeout(function() {
el.classList.remove("active")
}, 500)
}
})
.row {
transition: 500ms;
background: white;
}
.active {
background: yellow;
}
<div style="height: 400px">
scroll down
</div>
<div class="row">
this is a row
</div>
<div style="height: 400px">
scroll up
</div>

Use CSS to move cursor to another element

I'm trying to move the location of the cursor (mouse pointer) when an element is brought into view.
Let's say I have a button at the top of screen that, on click, opens a somewhere else on the screen. They are not connected in the doc flow (the is position: fixed>
When I show the new item, I want the mouse cursor to move to the newly displayed element, e.g. to the close button inside of it. I added a call to focus() but not working...
function myClick(idName) {
let listOfBios = document.getElementsByClassName("contents");
const len = listOfBios.length;
let elemName = "Content_" + idName;
let elem = document.getElementById(elemName);
elem.focus();
for(let i = 0; i < len; i++) {
let theBio = listOfBios[i];
if(theBio != elem){
//alert(elemName);
theBio.classList.remove("show_contents")
}
}
elem.classList.toggle("show_contents", 1);
elem.focus();
}
Assume that the rest of the code works, so I definitely have the right element ad toggle() is working.
You will need JS to achieve this. See below for example with vanilla JS.
in your view:
<input type="text" id="myTextField" value="Text field.">
in JS:
document.getElementById("myTextField").focus();
Check this fiddle:
https://jsfiddle.net/jz7v53tL/
Looks like it can't be done with just CSS and JS. Trying to close this out, I hope this is how.

Need angularJS dropdown width to fill whole screen from far left to far right.

I have an anglarJS project that has a horizontal navigation bar. Each element in the navigation bar is a category and uses an angularJS dropdown directive to show the subcategories for that category.
I would like the drop down to fill the whole screen from left to right. Currently the drop down determines it's width from the css "min-width" property. This does not solve my desire for the drop down menu to fill the whole screen I have seen some websites do this, and was wondering if there is a way to force my dropdown to fill the whole screen from left to right.
Here is the html for the page/drop down including the css that specifies the dropdown width.
Here is a picture of the dropdown again. I added blue arrows to indicate what I mean when I want the drop down to fill the whole screen.
The pictures are pretty high resolution and show you all the details. The page is rather complex to try and replicated in a plunker.
The whole thing needs to be responsive as well, and is based off of Bootstrap 3 and AngularJS Bootstrap.
Thanks for any help you can give!
David
I found a solution for the problem.
I created a button group that floats left that is on the same row as the button group in the center. The button group that floats left only contains one button, and that button has it's visibility set to hidden.
You have the dropdown attached to this button, rather than the ones in the center, since the dropdown won't start any farther left than the beginning of the button it is attached to.
<div class="pull-left">
<div class="btn-group" dropdown is-open="isOpen">
<button type="button" style="visibility: hidden" class="btn btn-link dropdown-toggle filter-criteria-variety-category-name" dropdown-toggle ng-disabled="disabled">
<span class="caret"></span>
</button>
<div class="dropdown-menu top-level-category-drop-down-standard" ng-style="{{windowWidth}}" ng-click="$event.stopPropagation()" >
<div ng-click="$event.stopPropagation()" ng-mouseleave="close()" ng-mouseenter="keepOpen()">
<div ng-if="currentCategory != undefined">
<horizontal-menu-inner close-drop-down-menu=$parent.closeDropDownMenu top-level-category=$parent.currentCategory></horizontal-menu-inner>
</div>
</div>
</div>
</div>
</div>
And for the centered button group that contains your categories you want to trigger the dropdown you pass the 'ioOpen' variable into the centered button directive as an attribute.
<div class="text-center">
<div class="btn-group">
<div class="horizontal-top-level-category" ng-repeat="topLevelCategory in categoryNavigationGraph">
<horizontal-top-level-category is-open=$parent.isOpen current-category-id=$parent.currentCategoryId top-level-category=topLevelCategory></horizontal-top-level-category>
</div>
</div>
</div>
You then have that directive set up to close or open the drop down depending on whether the mouse enters or leaves the button in that directive
<button ng-mousemove="activeMenuItemm()" ng-mouseleave="close($event)" ng-mouseenter="open()" type="button" ng-class="{'filter-criteria-variety-category-name-hover': filterCriteriaCategoryActive}" class="btn btn-link dropdown-toggle filter-criteria-variety-category-name" ng-disabled="disabled">
{{topLevelCategory.text}}
The tricky part is not having the dropdown close when you hover down from the centered button onto the dropdown
I did this by figuring out if the mouse was leaving from "down", which should not close the dropdown, or other, which should from the last position, which was calculated In the centered button directive link function:
link: function (scope, element) {
init();
scopeLevelFunctions();
function init(){
calculateBoundry();
}
function scopeLevelFunctions(){
scope.calculateElementBoundry = function(){
calculateBoundry();
}
}
function calculateBoundry(){
var boundry = element[0].getBoundingClientRect();
scope.boundry = boundry;
scope.topBoundry = boundry.top;
scope.bottomBoundry = boundry.bottom;
scope.leftBoundry = boundry.left;
scope.rightBoundry = boundry.right;
}
},
The open function triggered by mouseenter sets the boundry, which the close calculates from that value to see if this is a mouseleave that is leaving down
$scope.open = function(){
$scope.calculateElementBoundry();
$scope.currentCategoryId = $scope.topLevelCategory.categoryId;
$scope.filterCriteriaCategoryActive = true;
$scope.timeoutPromise = $timeout(function() {
$scope.isOpen = true;
}, 150);
};
$scope.close = function($event){
$scope.lastPosition = {
x : $event.clientX,
y : $event.clientY
};
var deltaX = $scope.lastPosition.x - $event.clientX,
deltaY = $scope.lastPosition.y - $event.clientY;
if($event.clientY >= ($scope.bottomBoundry - 8))
$scope.direction = "bottom";
else
$scope.direction = "other";
if($scope.direction != "bottom"){
if($scope.timeoutPromise != undefined)
$timeout.cancel(this.timeoutPromise);
$scope.isOpen = false;
$scope.filterCriteriaCategoryActive = false;
}
else{
if($scope.isOpen == false && $scope.timeoutPromise != undefined){
$timeout.cancel(this.timeoutPromise);
$scope.filterCriteriaCategoryActive = false;
}
}
I put the timeout in there so that if the user is just scrolling to bottom of the screen the drop down does not just appear. I cancel the timeout if they mouseleave and the drop down is not open.
The dropdown gets different data in it because the centered category directive has an attribute "categoryId" that is shared with the directive that the dropdown is located in. As that categoryId is changed that directive determines what that new categories submenu should be and feeds that into the dropdown.
I know how wide the dropdown should be because in the directive that contains the dropdown/invisible button I calculated the window width:
var width = $window.innerWidth;
$scope.windowWidth = "{'min-width':" + width + "}";
and on the dropdown I use ng-style to set this width
ng-style="{{windowWidth}}"

Change size property of an image using a text link

I am sure this is rediculously simple, but I'm stumped.
Very simply, I want to create a text link that changes the width property of an image on mouse over, and on mouse out, return to the original.
The image I wish to change has an id 'photoimage'
Here's what I have, but it's not doing anything. Any ideas>
<a href="#" onmouseover="MM_changeProp('photoimage','','Width','10','IMG')">
photographs
</a>
Sorry here is the function
function MM_changeProp(objId,x,theProp,theValue) { //v9.0
var obj = null; with (document){ if (getElementById)
obj = getElementById(objId); }
if (obj){
if (theValue == true || theValue == false)
eval("obj.style."+theProp+"="+theValue);
else eval("obj.style."+theProp+"='"+theValue+"'");
}
Any help much appreciated
Javascript:
function setWidth( elementId, width ) {
var element = getElementById(elementId);
element.style.width = width;
}
<a href="#"
onmouseover="setWidth('photoimage','200px')"
onmouseout="setWidth('photoimage', '100px')"> photographs </a>

How to hide jQuery Sub-Menus(ddsmoothmenu)?

I'm new to jQuery and i must admit that i've understood nothing yet, the syntax appears to me as an unknown language although i thought that i had my experiences with javascript.
Nevertheless i managed it to implement this menu in my asp.net masterpage's header.
Even got it to work that the content-page is loaded with ajax with help from here.
But finally i'm failing with the menu to disappear when the new page was loaded asynchronously. I dont know how to hide this accursed jQuery Menu.
Following the part of the js-file where the events are registered for hiding/disappearing. I dont know how to get the part that is responsible for it and even i dont know how to implement that part in my Anchor-onclick function where i dont have a reference to the jQuery Object.
buildmenu:function($, setting){
var smoothmenu=ddsmoothmenu
var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
$mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
var $headers=$mainmenu.find("ul").parent()
$headers.hover(
function(e){
$(this).children('a:eq(0)').addClass('selected')
},
function(e){
$(this).children('a:eq(0)').removeClass('selected')
}
)
$headers.each(function(i){ //loop through each LI header
var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
var $subul=$(this).find('ul:eq(0)').css({display:'block'})
$subul.data('timers', {})
this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
$subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
'<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
+'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
+ '" style="border:0;" />'
)
if (smoothmenu.shadow.enable){
this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
if (this.istopheader)
$parentshadow=$(document.body)
else{
var $parentLi=$curobj.parents("li:eq(0)")
$parentshadow=$parentLi.get(0).$shadow
}
this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'}) //insert shadow DIV and set it to parent node for the next shadow div
}
$curobj.hover(
function(e){
var $targetul=$subul //reference UL to reveal
var header=$curobj.get(0) //reference header LI as DOM object
clearTimeout($targetul.data('timers').hidetimer)
$targetul.data('timers').showtimer=setTimeout(function(){
header._offsets={left:$curobj.offset().left, top:$curobj.offset().top}
var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w
menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
if ($targetul.queue().length<=1){ //if 1 or less queued animations
$targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
if (smoothmenu.shadow.enable){
var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y
if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
header.$shadow.css({opacity:1})
}
header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
}
}
}, ddsmoothmenu.showhidedelay.showdelay)
},
function(e){
var $targetul=$subul
var header=$curobj.get(0)
clearTimeout($targetul.data('timers').showtimer)
$targetul.data('timers').hidetimer=setTimeout(function(){
$targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
if (smoothmenu.shadow.enable){
if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
header.$shadow.children('div:eq(0)').css({opacity:0})
}
header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
}
}, ddsmoothmenu.showhidedelay.hidedelay)
}
) //end hover
}) //end $headers.each()
$mainmenu.find("ul").css({display:'none', visibility:'visible'})
}
one link of my menu what i want to hide when the content is redirected to another page(i need "closeMenu-function"):
<li>Delivery Control</li>
In short: I want to fade out the submenus the same way they do automatically onblur, so that only the headermenu stays visible but i dont know how.
Thanks, Tim
EDIT: thanks to Starx' private-lesson in jQuery for beginners i solved it:
I forgot the # in $("#smoothmenu1"). After that it was not difficult to find and call the hover-function from the menu's headers to let them fade out smoothly:
$("#smoothmenu1").find("ul").hover();
Regards,
Tim
Ok, I didn't read your whole post. But if you are using a jQuery Menu, that menu should having a container element like <div> or <ul> and they will either have a class or id
In case it is a id then do
$(document).ready(function() {
$("#myelementid").hide();
});
In case it has a class then do
$(document).ready(function() {
$(".myelementclass").hide();
});
Hope this helps
UPDATE
$("#mainmenu").children().hide(); // to hide all child elements
or
$(".submenu").hide(); //to hide every submenu

Resources