I can't figure out how to acheive this, I have some elements with common_class class name, I want to get the ID of highest z-index element, is it possible?
function findHighestZIndex(elem)
{
var elems = document.getElementsByClassName(elem);
var highest = 0;
for (var i = 0; i < elems.length; i++)
{
var id = document.getElementsByClassName(elem);
id.getAttribute("id");
console.log(id);
var zindex=document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("z-index");
var ElementDisplay = document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("display");
if ((zindex > highest) && (zindex != 'auto') && (ElementDisplay == 'block'))
{
highest = zindex;
}
}
Here's a short, working implementation of a getHighest(selector) function, along with an example snippet that uses this function to retrieve id values (click the boxes to increment their z-index).
(The significant portion is the first three functions; they could be compressed into one function if needed.)
function getHighest(selector) {
// Return the element that matches selector having the largest z index
return Array.from(document.querySelectorAll(selector)).reduce((a, b) => getZIndex(a) >= getZIndex(b) ? a : b);
}
function getZIndex(el) {
// Return the z-index of el, or 0 if none is set.
return parseInt(getCssProperty(el, "z-index")) || 0;
}
function getCssProperty(el, prop) {
// Return the computed value of the css property prop for the element el
return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
}
// -------------------------------------------------------------------------
// additional code for demo below
// -------------------------------------------------------------------------
function updateHighest() {
let highest = getHighest(".box");
document.querySelector("#highest").textContent = `#${highest.id} (${getZIndex(highest)})`;
document.querySelector("#highest").style.color = getCssProperty(highest, "background-color");
}
function setContentToZIndex(el) {
el.textContent = getZIndex(el);
}
Array.from(document.querySelectorAll(".box")).forEach(b => {
b.onclick = () => {
b.style.zIndex = getZIndex(b) + 1;
setContentToZIndex(b);
updateHighest();
};
setContentToZIndex(b);
updateHighest();
});
.box {
width: 100px;
height: 100px;
display: block;
background: grey;
position: absolute;
color: white;
font-size: 2rem;
text-align: center;
line-height: 100px;
user-select: none;
font-family: sans-serif;
}
#b1 {
background: #ff268a;
left: 0px;
top: 0px;
}
#b2 {
background: #242792;
left: 50px;
top: 50px;
}
#b3 {
background: #0ac3d6;
left: 25px;
top: 75px;
}
p {
margin-left: 200px;
font-family: sans-serif;
font-size: 1.2rem;
}
<div class="box" id="b1"></div>
<div class="box" id="b2"></div>
<div class="box" id="b3"></div>
<p>highest z-index: <span id="highest"></span></p>
You could modify the function to return the element with the highest z-index, and then just use .id to get its id.
Another issue: You're comparing zindex and highest as strings instead of numbers. I've prefixed zindex with the unary + operator before comparing, as in your example, if you were to compare a z-index of 9 and a z-index of 1000, it would believe 9 is greater.
Example:
function findHighestZIndex(elem) {
var highest = 0;
var highestElement = null;
var elems = document.getElementsByClassName(elem);
for (var i = 0; i < elems.length; i++) {
var style = document.defaultView.getComputedStyle(elems[i], null);
var zindex = style.getPropertyValue("z-index");
var ElementDisplay = style.getPropertyValue("display");
if ((zindex != 'auto') && (+zindex > highest) && (ElementDisplay == 'block')) {
highest = zindex;
highestElement = elems[i];
}
}
return highestElement;
}
var elem = findHighestZIndex("zindex");
console.log(elem.id + " has the highest z-index.");
div.zindex {
z-index: 500;
position: absolute;
display: block;
}
<div id="first-element" class="zindex" style="z-index: 1;"></div>
<div id="second-element" class="zindex" style="z-index: 3;"></div>
<div id="third-element" class="zindex" style="z-index: 5;"></div>
<div id="fourth-element" class="zindex" style="z-index: 100;"></div>
<div id="fifth-element" class="zindex" style="z-index: 99;"></div>
If you are referring to not getting the id value here:
var elems = document.getElementsByClassName(elem);
var highest = 0;
for (var i = 0; i < elems.length; i++)
{
//This is all wrong here, commenting it out
//var id = document.getElementsByClassName(elem); //You already have this collection
//id.getAttribute("id"); //The above returns a collection so this would fail, you'd need to use an index of the collection
//console.log(id);
//You already have the elements you want, just use the i index to grab the element
//and it's id
console.log(elems[i].id);
You can use these functions:
function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function findHighestZIndex(className) {
let queryObject = document.getElementsByClassName(className);
let childNodes = Object.keys(queryObject).map(key => queryObject[key]);
let highest = 0;
var highestElem;
childNodes.forEach((node) => {
// Get the calculated CSS z-index value.
let cssStyles = document.defaultView.getComputedStyle(node);
let cssZIndex = cssStyles.getPropertyValue('z-index');
// Get any inline z-index value.
let inlineZIndex = node.style.zIndex;
// Coerce the values as integers for comparison.
cssZIndex = isNumeric(cssZIndex) ? parseInt(cssZIndex, 10) : 0;
inlineZIndex = isNumeric(inlineZIndex) ? parseInt(inlineZIndex, 10) : 0;
// Take the highest z-index for this element, whether inline or from CSS.
let currentZIndex = cssZIndex > inlineZIndex ? cssZIndex : inlineZIndex;
if ((currentZIndex > highest)) {
highest = currentZIndex;
highestElem = node;
}
});
var obj = {highestZIndex: highest, elem: highestElem};
return obj;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<html>
<body>
<div class="test" style="z-index: 100;" id="x">1</div>
<div class="test" style="z-index: 10;">2</div>
<div class='test' id="test">3</div>
<script>
function isNumeric(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function findHighestZIndex(className) {
let queryObject = document.getElementsByClassName(className);
let childNodes = Object.keys(queryObject).map(key => queryObject[key]);
let highest = 0;
var highestElem;
childNodes.forEach((node) => {
// Get the calculated CSS z-index value.
let cssStyles = document.defaultView.getComputedStyle(node);
let cssZIndex = cssStyles.getPropertyValue('z-index');
// Get any inline z-index value.
let inlineZIndex = node.style.zIndex;
// Coerce the values as integers for comparison.
cssZIndex = isNumeric(cssZIndex) ? parseInt(cssZIndex, 10) : 0;
inlineZIndex = isNumeric(inlineZIndex) ? parseInt(inlineZIndex, 10) : 0;
// Take the highest z-index for this element, whether inline or from CSS.
let currentZIndex = cssZIndex > inlineZIndex ? cssZIndex : inlineZIndex;
if ((currentZIndex > highest)) {
highest = currentZIndex;
highestElem = node;
}
});
var obj = {highestZIndex: highest, elem: highestElem};
return obj;
}
console.log(findHighestZIndex('test').elem.id);
</script>
</body>
</html>
</body>
</html>
Related
How can this script start counting from zero? At the moment it starts with the number it's supposed to count to before starting from zero
The JavaScript function loads the counter when it is called into view. How can the numerical values in the counter start with zeros when it is called into view
function isVisible(el) {
const element = $(el);
var WindowTop = $(window).scrollTop();
var WindowBottom = WindowTop + $(window).height();
var ElementTop = element.offset().top;
//var ElementBottom = ElementTop + element.height();
var ElementBottom = ElementTop + 20;
return ElementBottom <= WindowBottom && ElementTop >= WindowTop;
}
function Counter(el) {
obj = $(el);
if (obj.hasClass("ms-animated")) {
return;
}
obj.addClass("ms-animated");
// get the number
var number = obj.text();
obj.attr("data-number", number);
// clear the HTML element
obj.empty();
// create an array from the text, prepare to identify which characters in the string are numbers
var numChars = number.split("");
var numArray = [];
var setOfNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// for each number, create the animation elements
for (var i = 0; i < numChars.length; i++) {
if ($.inArray(parseInt(numChars[i], 10), setOfNumbers) != -1) {
obj.append(
'<span class="digit-con"><span class="digit' +
numArray.length +
'">0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br></span></span>'
);
numArray[numArray.length] = parseInt(numChars[i], 10);
} else {
obj.append("<span>" + numChars[i] + "</span>");
}
}
// determine the height of each number for the animation
var increment = obj.find(".digit-con").outerHeight();
var speed = 2000;
// animate each number
for (var i = 0; i < numArray.length; i++) {
obj
.find(".digit" + i)
.animate({
top: -(increment * numArray[i])
},
Math.round(speed / (1 + i * 0.333))
);
}
}
$(window).scroll(function() {
const counterNumbers = $(".number").toArray();
counterNumbers.filter(isVisible).map(Counter);
});
$(window).trigger("scroll");
.number {
display: block;
font-size: 6rem;
line-height: 6.5rem;
}
.number *+* {
margin-top: 0;
}
.digit-con {
display: inline-block;
height: 6.5rem;
overflow: hidden;
vertical-align: top;
}
.digit-con span {
display: block;
font-size: 6rem;
line-height: 6.5rem;
position: relative;
text-align: center;
top: 0;
width: 0.55em;
}
.month {
height: 100vh;
}
<h1>Scroll</h1>
<div class="number">$2,350,354.43</div>
<div class="month">March</div>
<div class="number">$6,350,354.43</div>
<div class="month">March</div>
<div class="number">$8,500,435.33</div>
<div class="month">April</div>
<div class="number">$3,500,435.53</div>
<div class="month">May</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>
Your issue is a something similar to FOUC - Flash of Unstyled Content - where what's originally in the HTML is displayed before it can be updated.
This can be fixed by changing the html and showing the value you want to display on load, while storing the required number in a data- attribute, eg:
<div class="number" data-number="$2,350,354.43">$0,000,000.00</div>
with a small change to your existing code to read the data- instead of text, from
var number = obj.text();
obj.attr("data-number", number); // this is never used
to
var number = obj.data("number");
If you can't change the html (or don't want to) then you can have an initialisation script run before your first scroll initialisation:
$(".number").each((i,e) => {
var obj = $(e);
var number = obj.text();
obj.data("number", number);
obj.text(number.replace(/\d/g, "0"));
});
You will still get FOUC on the very first counter if it's already visible because that's how javascript works: to keep things simple/basic: the page is rendered, then js runs. So there's a short time before the js runs where it's parsing/processing the js ready to run - how long this will be depends on how much js you have (including libraries) / whether it's cached / how much initialisation code there is.
Generally better to output your HTML as you want it displayed rather than rely on JS to update it, but that's not always possible.
Updated snippet:
function isVisible(el) {
const element = $(el);
var WindowTop = $(window).scrollTop();
var WindowBottom = WindowTop + $(window).height();
var ElementTop = element.offset().top;
//var ElementBottom = ElementTop + element.height();
var ElementBottom = ElementTop + 20;
return ElementBottom <= WindowBottom && ElementTop >= WindowTop;
}
function Counter(el) {
obj = $(el);
if (obj.hasClass("ms-animated")) {
return;
}
obj.addClass("ms-animated");
// get the number
//var number = obj.text();
//obj.attr("data-number", number);
var number = obj.data("number");
// clear the HTML element
obj.empty();
// create an array from the text, prepare to identify which characters in the string are numbers
var numChars = number.split("");
var numArray = [];
var setOfNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// for each number, create the animation elements
for (var i = 0; i < numChars.length; i++) {
if ($.inArray(parseInt(numChars[i], 10), setOfNumbers) != -1) {
obj.append(
'<span class="digit-con"><span class="digit' +
numArray.length +
'">0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br></span></span>'
);
numArray[numArray.length] = parseInt(numChars[i], 10);
} else {
obj.append("<span>" + numChars[i] + "</span>");
}
}
// determine the height of each number for the animation
var increment = obj.find(".digit-con").outerHeight();
var speed = 2000;
// animate each number
for (var i = 0; i < numArray.length; i++) {
obj
.find(".digit" + i)
.animate({
top: -(increment * numArray[i])
},
Math.round(speed / (1 + i * 0.333))
);
}
}
$(window).scroll(function() {
const counterNumbers = $(".number").toArray();
counterNumbers.filter(isVisible).map(Counter);
});
$(".number").each((i,e) => {
var obj = $(e);
var number = obj.text();
obj.data("number", number);
obj.text(number.replace(/\d/g, "0"));
});
$(window).trigger("scroll");
.number {
display: block;
font-size: 6rem;
line-height: 6.5rem;
}
.number *+* {
margin-top: 0;
}
.digit-con {
display: inline-block;
height: 6.5rem;
overflow: hidden;
vertical-align: top;
}
.digit-con span {
display: block;
font-size: 6rem;
line-height: 6.5rem;
position: relative;
text-align: center;
top: 0;
width: 0.55em;
}
.month {
height: 100vh;
}
<h1>Scroll</h1>
<div class="number">$2,350,354.43</div>
<div class="month">March</div>
<div class="number">$6,350,354.43</div>
<div class="month">March</div>
<div class="number">$8,500,435.33</div>
<div class="month">April</div>
<div class="number">$3,500,435.53</div>
<div class="month">May</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>
I am writing a javascript code which will sort arrays in ascending order. But whenever my code meets the correct condition which is arr[1] < arr[2], it stops the loop and prompts the message Congratulations!! This Group is Sorted By the way, I am using jquery also because I made a little game that you can sort all the numbers to ascending order and check if it is sorted or not.
I am not sure if the click event is responsible for the loop to stop. I am really confused with this. Can someone help me?
Here is the code snippet from my project:
HTML
<ul id="sort">
<!--Generated Numbers using javascript-->
</ul>
JAVASCRIPT
$(document).ready(function(){
$("#sort").sortable();
$("#sort").disableSelection();
// var elemArr = document.getElementsByClassName("sort-ui");
// var arr = jQuery.makeArray(elemArr);
// arr = arr.map(data => data.innerHTML);
var arr = [];
function generateNum(){
var min=1;
var max=12;
return Math.floor(Math.random() * (+max - +min)) + +min;
// document.write("Random Number Generated : " + random );
}
function storeToArray() {
var i = 0;
var ul = document.getElementById("sort");
var li;
while(i < 12) {
var rec = generateNum();
arr[i] = rec;
li = document.createElement("li");
li.appendChild(document.createTextNode(arr[i]));
ul.appendChild(li);
++i;
}
}
storeToArray();
$(".btn-check").on("click", function(){
var elemArr = document.getElementsByTagName("li");
var arrCheck = jQuery.makeArray(elemArr);
arrCheck = arrCheck.map(data => data.innerHTML);
var int;
var len = arrCheck.length;
console.log(arrCheck);
for(int = 0; int < len-1; i++) {
if(arrCheck[int] > arrCheck[int+1]){
alert("This Group is Not Sorted");
} else {
alert("Congratulations!! This Group is Sorted");
}
}
});
});
CSS (For you to visualize)
#sort {
list-style: none;
width: 430px;
border: 1px solid;
padding: 20px;
margin: 0 auto;
height: 315px;
}
#sort li {
display: inline-block;
float: left;
width: 100px;
height: 100px;
background: yellow;
font: 600 16px/100px "Arial";
text-align: center;
margin: 0;
border: 3px solid white;
}
.button-c {
width: 200px;
margin: 0 auto;
}
There is mistake in for loop i++ for(int = 0; int < len-1; i++) , It should be int++
let arrCheck = [1, 3 , 3, 4]
let len = arrCheck.length
for(let int = 0; int < len-1; int++) {
if(arrCheck[int] > arrCheck[int+1]){
alert("This Group is Not Sorted");
} else {
alert("Congratulations!! This Group is Sorted");
}
}
Your implementation of the sort function was incorrect. You didn't use the break keyword and your numbers were in string format, so you need to parse them for comparison.
function isSorted(arrCheck) {
var sortVal = true;
var len = arrCheck.length;
console.log(arrCheck);
for(int = 0; int < len-1; int++) {
if(parseInt(arrCheck[int]) > parseInt(arrCheck[int+1])) {
sortVal = false;
break;
}
}
return sortVal;
}
I want to add 10 points when blue box goes into brown box.
I tried to set score = 0 and points to add = 10 but it doesn't work.
I alert '+10 points' and it shows me the alert so I guess the problem is the DOM ?!?
Any suggestions ?
Thanks !
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 10) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
if ($(".p-0").hasClass("ob")) {
alert('add +10 points !!!')
addPoints.text( parseInt(addPoints.text()) + obs );
}
moveCounter += 1;
if ($(".p-0").hasClass("ob")) {
}
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.ob {
background-color: brown;
}
.p-0 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div id="score">
</div>
Thank you very much! I am new to JavaScript/ JQuery
Thank you very much!
You are trying to change the HTML inside of the div with id "score".
Selecting the css element using $("#id") retrieves the DOM element and not its contents so adding the score directly to it has no consequences.
What you want to do is: update the score variable and then set the HTML inside the div to the score value.
So instead of just:
addPoints += obs
you should
score += obs
addPoints.html(score)
I would like to know how can I define a bigger variable for a set of variables that I have in javascript: showFootnotesPanel();, showReferencesPanel();, showImagesPanel();, showInformationPanel();.
Would it be something like this?
function showPanel() {
var x = [showFootnotesPanel();showReferencesPanel();showImagesPanel();showInformationPanel();]
}
Update:
I have this function that used to open a side panel on the right side and color the content:
var els = document.getElementsByClassName('change-color'),
target = document.getElementsByClassName('resources'),
changeColor = function(a) {
elements = document.getElementsByClassName("note");
for (var i = 0; i < elements.length; i++) {
console.log(elements[i])
elements[i].style.backgroundColor = "";
}
target = a.getAttribute('href');
element = document.querySelector('[data-id="' + target.substring(1, target.length) + '"]');
element.style.backgroundColor = a.getAttribute('data-color');
};
for (var i = els.length - 1; i >= 0; --i) {
els[i].onclick = function() {
showFootnotesPanel();
changeColor(this);
}
Now I have 4 side panels that need to respond to the same script, and I thought that by defining something like showPanel() is showFootnotesPanel() or showReferencesPanel() or showImagesPanel() or showInformationPanel() I might simplify things, so the last line of the script would be this instead just:
els[i].onclick = function(){showPanel();changeColor(this);}
Update 2:
Or is it possible to do this with the logical operator OR?
els[i].onclick = function(){showFootnotesPanel(); || showReferencesPanel(); || showImagesPanel(); || showInformationPanel();changeColor(this);}
Update 3:
This is the new script that I am using to hide and show the panels:
function showPanel(myPanel) {
var elem = document.getElementById(myPanel);
if (elem.classList) {
console.log("classList supported");
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
function hideOthers(one, two, three, four) {
if (one > "") {
var elem1 = document.getElementById(one);
var classes = elem1.className;
elem1.className = classes.replace("show", "");
}
if (two > "") {
var elem2 = document.getElementById(two);
var classes = elem2.className;
elem2.className = classes.replace("show", "");
}
if (three > "") {
var elem3 = document.getElementById(three);
var classes = elem3.className;
elem3.className = classes.replace("show", "");
}
if (four > "") {
var elem4 = document.getElementById(four);
var classes = elem4.className;
elem4.className = classes.replace("show", "");
}
return;
}
And this is the script that calls the panels and highlights the text on them:
var els = document.getElementsByClassName('change-color'),
target = document.getElementsByClassName('resources'),
changeColor = function(a) {
elements = document.getElementsByClassName("note");
for (var i = 0; i < elements.length; i++) {
console.log(elements[i])
elements[i].style.backgroundColor = "";
}
target = a.getAttribute('href');
element = document.querySelector('[data-id="' + target.substring(1, target.length) + '"]');
element.style.backgroundColor = a.getAttribute('data-color');
};
for (var i = els.length - 1; i >= 0; --i) {
els[i].onclick = function() {
hideOthers('footnotes-section', 'references-section', 'images-section', 'information-section');
showPanel('references-section');
changeColor(this);
}
}
Thank you!
Updated with a final solution.
In javascript you can declare variables by this way:
var text = ""; // String variable.
var number = 0; //Numeric variable.
var boolValue = true; //Boolean variable.
var arrayValue = []; // Array variable. This array can contain objects {}.
var obj = {}; // Object variable.
Check this version of your code.
// var text = ""; => String variable.
// var number = 0; => Numeric variable.
// var boolValue = true; => Boolean variable.
// var arrayValue = []; => Array variable. This array can contain objects {}.
// var obj = {}; => Object variable.
// This section of code is only to explain the first question.
(function() {
function showFootnotesPanel() {
return 10; // Random value.
}
function showReferencesPanel() {
return 30; // Random value.
}
function showImagesPanel() {
return 50; // Random value.
}
function showInformationPanel() {
return 90; // Random value.
}
function showPanel() {
return [
showFootnotesPanel(), // Index = 0
showReferencesPanel(), // Index = 1
showImagesPanel(), // Index = 2
showInformationPanel() // Index = 3
];
}
var bigVariable = showPanel(); // bigVariable is array of numeric values.
// Using logical operator to check status of variable about this demo code.
if (bigVariable[0] === 10 || bigVariable[1] === 30) {
console.log("Hey, with these values can show the FootnotesPanel and ReferencesPanel.");
} else {
console.log("With the current values can't show anything...");
}
console.log(bigVariable);
})();
// https://jsfiddle.net/dannyjhonston/t5e8g22b/
// This section of code attempts to answer the question of this post.
(function() {
// This function can be executed when the page is loaded.
function showPanel(panels) {
var panel, panelVisible = "";
var selPanels = document.getElementById("selPanels");
// In panels array...
for (var i = 0; i < panels.length; i++) {
// panels[0] = "ReferencesPanel";
panel = document.getElementById(panels[i]); // Get in the DOM tag context of the panel to set in the variable "panel".
panelVisible = panel.getAttribute("data-visible"); // HTML5 data attribute.
if (panelVisible == "true") {
panel.setAttribute("class", "show");
} else {
panel.setAttribute("class", "hide");
}
}
}
// This function is for set panel visibilty.
function setPanel(panelId, status) {
panel = document.getElementById(panelId);
panel.setAttribute("data-visible", status);
// Calling the showPanel function to check in the DOM.
showPanel(["ReferencesPanel", "InformationPanel", "ImagesPanel", "FootnotesPanel"]);
}
// Binding the change event to the select tag.
selPanels.addEventListener("change", function() {
// Executes setPanel function with panelId and true to update the data-visible attribute in the DOM.
setPanel(this.options[this.selectedIndex].value, "true");
});
// Executes showPanel function with array argument with panels Id. You need to specify every panel that want to handle.
showPanel(["ReferencesPanel", "InformationPanel", "ImagesPanel", "FootnotesPanel"]);
})();
#global {
border: solid 1px #6291AD;
}
.tools {
background-image: linear-gradient(#FFFFFF, #8999CE);
}
#global div[data-visible] {
height: 80px;
padding: 5px 0;
}
#global div p {
padding: 10px;
}
#ReferencesPanel {
background-image: linear-gradient(#FFFFFF, #FD9A9A);
float: left;
width: 20%;
}
#InformationPanel {
background-image: linear-gradient(#FFFFFF, #A1C7F1);
float: left;
width: 80%;
}
#ImagesPanel {
background-image: linear-gradient(#C6E9FB, #FFF);
width: 100%;
}
#FootnotesPanel {
background-image: linear-gradient(#C6E999, #FFF);
width: 100%;
}
.clear {
clear: both;
}
.show {
display: block;
}
.hide {
display: none;
}
<div id="global">
<div class="tools">Show Panel:
<br />
<!-- Demo -->
<select id="selPanels">
<option value="">[SELECT]</option>
<option value="ReferencesPanel">ReferencesPanel</option>
<option value="InformationPanel">InformationPanel</option>
<option value="ImagesPanel">ImagesPanel</option>
<option value="FootnotesPanel">FootnotesPanel</option>
</select>
</div>
<!-- You need to set data-visible attribute with true or false to show or hide a panel. -->
<div id="ReferencesPanel" data-visible="false">
<p>References Panel</p>
</div>
<div id="InformationPanel" data-visible="false">
<p>Information Panel</p>
</div>
<div class="clear"></div>
<div id="ImagesPanel" data-visible="false">
<p>Images Panel</p>
</div>
<div id="FootnotesPanel" data-visible="false">
<p>Foot notes Panel</p>
</div>
</div>
I dont understand your question exactly, but if you want to define a variable that contains other variables then you can use an object.
e.g:
var footNotesPanel = true;
var referencesPanel = true;
var imagesPanel = true;
var showPanels = {
footNotesPanel: footNotesPanel,
referencesPanel: referencesPanel,
imagesPanel: imagesPanel
}
/*
Option 2 - for showing/hiding side panels
1 ) create all your panels as they would appear, with all the data, but hide them with display:none;
2 ) call show panel function to show a panel.
*/
var showPanel(panel_id) {
var panel_element = $("#" + panel_id); /*panel that you want to show ( is hidden atm but somewhere on the page */
if (!panel_element.length) {
return false; //no panel with this id currently on page
} else {
//check the panel id and do some custom editing if needed, eg.
if (panel_id == "main_side_panel") {
//add some additional classes to body element etc
}
panel_element.show();
//Or Another option that you probably are looking for is below
if (panel_id == "footnotes_panel") {
showFootnotesPanel();
} else if (panel_id == "images_panel") {
showImagesPanel();
}
}
}
// And use it like this:
<div id="footnotes_panel" onclick="showPanel('footnotes_panel')"></div>
// Or simply get the element id from `event.target` and use `showPanel()` without arguments.
I need to compare two elements offset positions to find whether one element is placed above on other element.
here i need to check the me is placed on the screen or not by using offset positions.
HTML Code
<div id="screen" style="background-color: olive; height: 120px; width:120px;"></div>
<span id="me" style="position: absolute; left: 44px; top: 86px;">me</span></div>
JavaScript
var a = document.getElementById('screen')
var b = document.getElementById('me');
aOffsetLeft=a.offsetLeft;
aOffsetTop=a.offsetTop;
bOffsetLeft=b.offsetLeft;
bOffsetTop=b.offsetTop;
//Here need to check whether b within a
Please help me
Above code is in jquery, below is javascript code :
https://jsfiddle.net/7xudznea/11/
var a = document.getElementById('screen')
var b = document.getElementById('me');
var c = document.getElementById('abc');
aOffsetLeft = a.offsetLeft;
aOffsetTop = a.offsetTop;
aoffsetHeight = a.offsetHeight;
aoffsetoffsetWidth = a.offsetoffsetWidth;
bOffsetLeft = b.offsetLeft;
bOffsetTop = b.offsetTop;
if ((aoffsetHeight + aOffsetTop >= bOffsetTop) || (aoffsetoffsetWidth + aOffsetLeft >= bOffsetLeft)) {
document.getElementById('abc').innerHTML = 'true';
} else {
document.getElementById('abc').innerHTML = 'false';
}
var $screen = $('#screen');
var $me = $('#me');
if ((($screen.height() + $screen.offset().top) >= $me.offset().top) || ($screen.width() + $screen.offset().left >= $me.offset().left)) {
return true;
} else {
return false;
}
Demo: https://jsfiddle.net/7xudznea/6/