I have a 4 div elements each with their own value, for example 0. I have a button with a plus and minus that changes the value in each box. I also have a set next button so you can do the same thing to the next box.
The problem I'm facing is how to select the next div and change the value with the same plus and minus buttons and then selecting the next div and doing the same until you're at the end. It then has to return to the first div. Here is my code:
<div class="code_div">
<div class="code_area">
<p id="number1">00</p>
</div>
<div class="code_area2">
<p id="number2">00</p>
</div>
<div class="code_area3">
<p id="number3">00</p>
</div>
<div class="code_area4">
<p id="number4">00</p>
</div>
var value = 0;
var plus = false;
var minus = false;
$(document).ready(function() {
$('#set_next').click(function() {
});
$('#minus').click(function() {
minus = false;
plus = true;
if (plus == true) {
value -= 5;
}
displayValue()
});
$('#plus').click(function() {
minus = true;
plus = false;
if (minus == true) {
value += 5;
}
displayValue()
});
});
function displayValue() {
document.getElementById("number1").innerHTML = value;
}
Can anyone help me?
Keep it simple. You have a list of divs, so use a list instead. Even if you want to keep your original markup, this should give an idea on how to implement this.
var $items = $('ul li'),
qtItems = $items.length,
activeItem = 0;
$('#setnext').click(function () {
$items.removeClass('active').eq(++activeItem % qtItems).addClass('active');
});
$('#plus, #minus').click(function () {
var currvalue = $items.eq(activeItem % qtItems).text();
this.id === 'plus' ? currvalue++ : currvalue--;
$items.eq(activeItem % qtItems).text(currvalue);
});
ul {
list-style: none;
}
ul li {
display: inline-block;
margin: 0 1em;
padding: 1em;
background-color: green;
opacity: .5;
}
li.active {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="active">0</li>
<li>0</li>
<li>0</li>
<li>0</li>
</ul>
<button id="setnext">set next</button>
<button id="plus">plus</button>
<button id="minus">minus</button>
But, if you cannot simplify your markup, here is another simple solution using your original html.
As you can see, you don't need all of those classes and ids.
var value = 0;
var plus = false;
var minus = false;
var index=1;
$( document ).ready(function() {
$('#set_next').click(function() {
index++;
//update
$("#number"+index).css("color","blue");
if(index==5){
index=1;
}
});
$('#minus').click(function() {
minus = false;
plus = true;
if (plus == true){
value -= 5;
}
displayValue()
});
$('#plus').click(function() {
minus = true;
plus = false;
if (minus == true){
value += 5;
}
displayValue()
});
});
function displayValue(){
document.getElementById("number"+index).innerHTML = value;
}
Although your code needs a lot of polishing (i can give you a cleaner approach if you want)
https://jsfiddle.net/cbw4zc55/
something along these lines?
html code:
<div class="code_div">
<div class="code_area">
<p id="number1">00</p>
</div>
<div class="code_area2">
<p id="number2">00</p>
</div>
<div class="code_area3">
<p id="number3">00</p>
</div>
<div class="code_area4">
<p id="number4">00</p>
</div>
<button id="set_next">set next</button>
<button id="minus">minus</button>
<button id="plus">plus</button>
javascript:
var current = 1;
var max = 4;
var value = 0;
var plus = false;
var minus = false;
$( document ).ready(function() {
$('#set_next').click(function() {
if( current < max )
{
current+=1;
}
else
{
current = 1;
}
value = parseInt($("#number"+current).text());
});
$('#minus').click(function() {
minus = false;
plus = true;
if (plus == true){
value -= 5;
}
displayValue()
});
$('#plus').click(function() {
minus = true;
plus = false;
if (minus == true){
value += 5;
}
displayValue()
});
});
function displayValue(){
document.getElementById("number"+current).innerHTML = value;
}
EDIT:
Note that you would need to recalculate the current element value each time you change your focus to a new one (aside from that the selected answer is just perfect as well)
Related
I have a JSFiddle that shows my code now:
https://jsfiddle.net/qtu1xgw3/2/
Basically there is an image button (pink flower) and then there are 4 images that change when the button is clicked.
Now the issue is that I want the button to hide when I get to the last image. Right now I need to click the button twice to get it to hide on the last image. But I want with the last click of the button to hide it at the same time that the last image in the gallery is shown.
One of the images is in the html part of the code, which might be what causes this issue, I think, but I'm not sure how to do this differently without breaking the code?
(random images from google used for the sake of testing)
HTML:
<div class="test">
<div class="desc">
<h2 id="title_text">test1</h2>
<p id="under_text">test2</p>
</div>
<div id="pink">
<img src="https://images.vexels.com/media/users/3/234325/isolated/lists/cba2167ec09abeeee327ffa0f994151b-detailed-flower-illustration.png" onclick="imagefun()"></div>
<div class="game">
<img src="https://images.vexels.com/media/users/3/143128/isolated/lists/2a84565e7c9642368346c7e6317fa1fa-flat-flower-illustration-doodle.png" id="getImage"></div>
</div>
CSS:
.game img {
width: 300px;
height: auto;
}
.test {
display: flex;
flex-direction: row;
}
JS:
var counter = 0,
gallery = ["https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/914750/aab494aa7cde1991d0a86cc28ec6debdbee37d7f.jpg", "https://api.assistivecards.com/cards/gardening/flowers.png", "https://i.pinimg.com/474x/7d/10/75/7d1075cf259131c942037683d2243bb0.jpg"],
imagefun = function () {
if (counter >= gallery.length) {
document.getElementById("title_text").innerHTML = "test3"; document.getElementById("under_text").innerHTML = "test4"; document.getElementById("pink").style.display = "none";
}
else{
document.getElementById("getImage").src = gallery[counter];
counter++;
}
};
I have made some change to your code. It will help you.
var counter = 0,
gallery = ["https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/914750/aab494aa7cde1991d0a86cc28ec6debdbee37d7f.jpg", "https://api.assistivecards.com/cards/gardening/flowers.png", "https://i.pinimg.com/474x/7d/10/75/7d1075cf259131c942037683d2243bb0.jpg"],
imagefun = function () {
if (counter == gallery.length -1) {
document.getElementById("getImage").src = gallery[counter];
document.getElementById("pink").style.display = "none";
}
else{
document.getElementById("getImage").src = gallery[counter];
counter++;
}
};
try this
Evaluate when the counter is equal to the size of your array if so then do the job you want
imagefun = function () {
if(counter==gallery.length)
{
document.getElementById("getImage").style.display = "none";
}
if (counter >= gallery.length) {
document.getElementById("title_text").innerHTML = "test3";
document.getElementById("under_text").innerHTML = "test4";
document.getElementById("pink").style.display = "none";
}
else{
document.getElementById("getImage").src = gallery[counter];
counter++;
}
};
The issue is that you increment your counter after the counter >= gallery.length check.
The correct solution is:
const gallery = [
"https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/914750/aab494aa7cde1991d0a86cc28ec6debdbee37d7f.jpg",
"https://api.assistivecards.com/cards/gardening/flowers.png",
"https://i.pinimg.com/474x/7d/10/75/7d1075cf259131c942037683d2243bb0.jpg",
];
let counter = 0;
document.getElementById("getImage").src = gallery[counter];
function imagefun() {
counter += 1;
document.getElementById("getImage").src = gallery[counter];
if (counter >= gallery.length - 1) {
document.getElementById("title_text").innerHTML = "test3";
document.getElementById("under_text").innerHTML = "test4";
document.getElementById("pink").style.display = "none";
}
};
I've got a simple number input with a min="1" and max="12" value set, this is used as an hour selector. I'd like it to cycle through the hours, so when you get to 12 and press the "up" arrow, it goes back to 1 and vice-versa as well.
Right now I have this mostly working:
var inputTimer = null;
function cycle(element) {
if (element.attributes.max && element.attributes.min) {
var prevVal = element.value;
inputTimer = setTimeout(function() {
if (prevVal === element.attributes.max.value) {
element.value = element.attributes.min.value;
} else if (prevVal === element.attributes.min.value) {
element.value = element.attributes.max.value;
}
}, 50);
}
}
$("input[type='number']")
.on("mousedown", function(e) {
//this event happens before the `input` event!
cycle(this);
}).on('keydown', function(e) {
//up & down arrow keys
//this event happens before the `input` event!
if (e.keyCode === 38 || e.keyCode === 40) {
cycle(this);
}
}).on('input', function(e) {
//this event happens whenever the value changes
clearTimeout(inputTimer);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" min="1" max="12" value="12" />
Working DEMO
The issue I have is that I can't find a way to detect if the arrow spinners in the input have been clicked, or just the input as a whole has been clicked. Right now it has an issue where it changes the value when you click anywhere in the field when the value is currently at 1 or 12
Is there a way to detect if the click event occurs on the spinners/arrows within the text field?
You have to handle the input event, like this:
$('[type=number]').on('input',function(){
this.value %= 12 ;
if( this.value < 1 )
this.value -= -12 ;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=number>
I searched a lot and it seems there is no way to natively detect that. That makes this one a very important question because I think this should be added to new versions of HTML.
There are many possible workarouds. They all fail on the problem the it's impossible to know, in which direction is value going. I decided to use mouse position information to detect, whether is user increasing or decreasing a value. It works, but does not properly handle the situation, when user holds the button.
var inputTimer = null;
function cycle(event) {
var value = this.value;
// Value deep within bonds -> no action
if(value>this.min && value<this.max) {
return;
}
// Check coordinate of the mouse
var x,y;
//This is the current screen rectangle of input
var rect = this.getBoundingClientRect();
var width = rect.right - rect.left;
var height = rect.bottom-rect.top;
//Recalculate mouse offsets to relative offsets
x = event.clientX - rect.left;
y = event.clientY - rect.top;
// Now let's say that we expect the click only in the last 80%
// of the input
if(x/width<0.8) {
console.log("Not click on arrows.", x, width);
return;
}
// Check "clicked button" by checking how high on input was clicked
var percentHeight = y/height;
// Top arrow was clicked
if(percentHeight<0.5 && value==this.max) {
this.value = this.min;
event.preventDefault();
return false;
}
// Bottom arrow was clicked
if(percentHeight>0.5 && value==this.min) {
this.value = this.max;
event.preventDefault();
return false;
}
}
var input = document.getElementById("number");
input.addEventListener("mousedown", cycle);
<input id="number" type="number" min="1" max="12" value="12" />
A method you could try is by using the Attributes of the element to track what the previous value is. This isn't, of course, actually tracking which button got hit but it's the closest I've been able to get.
JS:
$(document).ready(function() {
function Init(){
var test = document.getElementById('test');
test.setAttribute('prev', 0);
}
Init()
$('#test').on('input', function() {
var test = document.getElementById('test')
var d = test.value - test.getAttribute('prev');
console.log(d);
test.setAttribute('prev', test.value);
});
});
HTML:
<input type="number" id="test">
Then all you would have is logic that says if d(irection) is positive, they clicked up. If negative, they clicked down. If it's 0 then they didn't click a button.
Working Fiddle
I think this is what you really want.
<input type="time" value="01:00" step="600"/>
There is currently no native way to capture the arrow input events separate from the input box events. Everything using number input seems to be kinda hacky for this purpose.
Next best option is something like http://jdewit.github.io/bootstrap-timepicker/
This doesn't work for your specific situation where you have a maximum and want it to wrap, but it might be helpful for others who want to process the field value based on changes via arrows, such as for setting .toFixed(2) to a currency value like I needed:
document.getElementById('el').setAttribute('data-last',document.getElementById('el').value);
document.getElementById('el').addEventListener('keyup', function(){
this.setAttribute('data-last',this.value);
});
document.getElementById('el').addEventListener('click', function(){
if(this.value>this.getAttribute('data-last')) console.log('up clicked');
if(this.value<this.getAttribute('data-last')) console.log('down clicked');
});
This is my code written in JQuery , this one can implement auto-increment ( + & - ) long-press spin buttons .
$.fn.spinInput = function (options) {
var settings = $.extend({
maximum: 1000,
minimum: 0,
value: 1,
onChange: null
}, options);
return this.each(function (index, item) {
var min = $(item).find('>*:first-child').first();
var max = $(item).find('>*:last-child').first();
var v_span = $(item).find('>*:nth-child(2)').find('span');
var v_input = $(item).find('>*:nth-child(2)').find('input');
var value = settings.value;
$(v_input).val(value);
$(v_span).text(value);
async function increment() {
value = Number.parseInt($(v_input).val());
if ((value - 1) > settings.maximum) return;
value++;
$(v_input).val(value);
$(v_span).text(value);
if (settings.onChange) settings.onChange(value);
}
async function desincrement() {
value = Number.parseInt($(v_input).val());
if ((value - 1) < settings.minimum) return;
value--
$(v_input).val(value);
$(v_span).text(value);
if (settings.onChange) settings.onChange(value);
}
var pressTimer;
function actionHandler(btn, fct, time = 100, ...args) {
function longHandler() {
pressTimer = window.setTimeout(function () {
fct(...args);
clearTimeout(pressTimer);
longHandler()
}, time);
}
$(btn).mouseup(function () {
clearTimeout(pressTimer);
}).mousedown(function () {
longHandler();
});
$(btn).click(function () {
fct(...args);
});
}
actionHandler(min, desincrement, 100);
actionHandler(max, increment, 100)
})
}
$('body').ready(function () {
$('.spin-input').spinInput({ value: 1, minimum: 1 });
});
:root {
--primary-dark-color: #F3283C;
--primary-light-color: #FF6978;
--success-dark-color: #32A071;
--sucess-light-color: #06E775;
--alert-light-color: #a42a23;
--alert-dark-color: #7a1f1a;
--secondary-dark-color: #666666;
--secondary-light-color: #A6A6A6;
--gold-dark-color: #FFA500;
--gold-light-color: #FFBD00;
--default-dark-color: #1E2C31;
--default-light-color: #E5E5E5;
}
.fx-row {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.fx-colum {
display: flex;
flex-direction: column;
flex-wrap: wrap;
}
.fx-colum.nowrap,
.fx-row.nowrap {
flex-wrap: nowrap;
}
.fx-row.fx-fill>*,
.fx-colum.fx-fill>* {
flex-grow: 1;
}
.spin-input {
border: 1px solid var(--secondary-light-color);
}
.spin-input>div:first-child {
cursor: pointer;
border-right: 1px solid var(--secondary-light-color);
}
.spin-input>div:first-child:active {
transform: translate3d(1px, 0px, 1px)
}
.spin-input>div:last-child {
flex: none;
border-left: 1px solid var(--secondary-light-color);
cursor: pointer;
}
.spin-input>div:last-child:active {
transform: translate3d(1px, 0px, 1px)
}
.icon {
font-weight: bold;
text-align: center;
vertical-align: middle;
padding: 12px;
font-size: 28px;
}
.icon.primary,
.icon.primary .ci {
color: var(--primary-dark-color);
}
.icon.reactive:hover .ci {
color: var(--primary-light-color);
}
.hidden {
display: none;
}
<script src="https://releases.jquery.com/git/jquery-3.x-git.min.js"></script>
<div class="spin-input nowrap fx-row fx-fill" >
<div class="icon reactive">
<span class="ci ci-minus">-</span>
</div>
<div class="icon">
<span>0</span>
<input type="text" class="hidden" value="0">
</div>
<div class="icon reactive">
<span class="ci ci-plus">+</span>
</div>
</div>
There is my jQuery plugin , I hope that can help you .
So I am not sure there is anyway to determine what is being clicked, be it field input or little arrows, but I was able to get it working like this.
Fiddle: http://jsfiddle.net/nusjua9s/4/
JS:
(function($) {
var methods = {
cycle: function() {
if (this.attributes.max && this.attributes.min) {
var val = this.value;
var min = parseInt(this.attributes.min.value, 10);
var max = parseInt(this.attributes.max.value, 10);
if (val === this.attributes.max.value) {
this.value = min + 1;
} else if (val === this.attributes.min.value) {
this.value = max - 1;
} else if (!(val > min && val < max)) {
// Handle values being typed in that are out of range
this.value = $(this).attr('data-default');
}
}
}
};
$.fn.circularRange = function() {
return this.each(function() {
if (this.attributes.max && this.attributes.min) {
var $this = $(this);
var defaultVal = this.value;
var min = parseInt(this.attributes.min.value, 10);
var max = parseInt(this.attributes.max.value, 10);
$this.attr('min', min - 1);
$this.attr('max', max + 1);
$this.attr('data-default', defaultVal);
$this.on("change", methods.cycle);
}
});
};
})(jQuery);
$("input[type='number']").circularRange();
HTML:
<input type="number" min="1" max="12" value="12" />
So I am not sure why I keep thinking about this and it still doesn't solve what you are seeing with the flash of out of range numbers which I don't see. But now its not confusing to setup the html ranges at least. You can set the range you want without thinking and just initialize the type="number" fields.
Try with $('input[type="number"]').change(function() {}); ? No result ?
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/
I'm using "float: left" to place blocks in container. Like this on large screen:
on small scree:
can i select last element on row when user clicks on any element?
If the elements are all inline or floating then there wont be a concept of a "last element on row".
I suggest you calculate the element using known values:
$('.box').on('click', function (e) {
// calculate how many boxes will be in a "row"
var windowWidth = $('ul').width();
var boxWidth = $('.box').outerWidth();
var boxesPerRow = ~~(windowWidth / boxWidth);
// get the index of the clicked element
var index = $(e.currentTarget).index();
// get the column of the clicked element
var col = (index % boxesPerRow) + 1;
// calculate how far it is to the end of this row,
// and select that element
var $endOfRow = $('.box').eq(index + boxesPerRow - col);
if (!$endOfRow.length) $endOfRow = $('.box').last();
});
Updated my answer with one that works. Here's the fiddle: http://jsfiddle.net/gvbw9Lkz/4/
As an alternative you can dynamically work out which elements are in the same row by comparing their position() values:
$(function() {
// cache the collection of all the blocks
var blocks = $('.block');
blocks.on('click', function() {
blocks.removeClass('highlight');
var $this = $(this);
// get the y coordinate of the clicked block
var y = $this.position().top;
// store the blocks in the row
var rowBlocks = $this;
// search backwards until we find a different y coordinate or reach 0
for (var i = $this.index() - 1; i >= 0; i--) {
var block = blocks.eq(i);
if (block.position().top == y) {
// add the element to the rowBlocks selector
rowBlocks = rowBlocks.add(block);
} else {
// different coordinate, stop searching
break;
}
}
// search forwards until we find a different y coordinate or reach the end
for (var i = $this.index() + 1; i < blocks.length; i++) {
var block = blocks.eq(i);
if (block.position().top == y) {
// add the element to the rowBlocks selector
rowBlocks = rowBlocks.add(block);
} else {
// different coordinate, stop searching
break;
}
}
// hightlight the row
rowBlocks.addClass('highlight');
});
});
.container {
width: 300px;
}
.block {
background-color: #000;
width: 50px;
height: 50px;
margin: 10px;
float: left;
}
.block.highlight {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<div class="block">1</div>
<div class="block">2</div>
<div class="block">3</div>
<div class="block">4</div>
<div class="block">5</div>
<div class="block">6</div>
<div class="block">7</div>
<div class="block">8</div>
<div class="block">9</div>
<div class="block">10</div>
<div class="block">11</div>
<div class="block">12</div>
<div class="block">13</div>
<div class="block">14</div>
<div class="block">15</div>
<div class="block">16</div>
<div class="block">17</div>
<div class="block">18</div>
<div class="block">19</div>
<div class="block">20</div>
</div>