Here's the JavaScript code you can find everywhere when you want to hide/show an element:
function sh(_id, _val) {
if (document.getElementById) {
document.getElementById(_id).style.display = _val;
}
else {
if (document.layers) {
document._id.display = _val;
}
else {
document.all._id.style.display = _val;
}
}
}
function hide(_id) {
sh(_id, 'none');
}
function show(_id) {
sh(_id, 'block');
}
The problem is the "show" function: it forces to "block". If I use a table with tr's and td's, when I want to display them I don't them to be displayed as "block" but to restore to their initial state.
How should I do?
How would you do?
If you want to restore their default display value, you can assign an empty string to it:
element.style.display = '';
If you want the one assigned through CSS for example, you have to store it somewhere, e.g. in an id -> display map or as data- attribute.
The easiest way would be to use jQuery and .show() http://api.jquery.com/show/
The second easiest way would be to wrap the table in a div.
If not I would try to store the initial value of display somewhere (if html5 the a "data-" attribute) if not in some other hidden element
If the point of your exercise is to learn more about DOM, then you may disregard this answer. But if the point is to get some UI to work, then:
My suggestion would be to use jquery. If you did, all of the code you showed would disappear altogether, and you would hide/show elements like this:
$('#' + id).hide()
$('#' + id).show()
If you want to stick with low level DOM api, then you'll have to save away the prior value (block or whatever) of style.display, so you can restore it later. And you can do that. But you'll keep having to write code like that, considering all kinds of cases, when someone has already written code that does that, and they're giving it away for free.
var previousDisplay = {};
function sh(_id, _val) {
if (document.getElementById) {
document.getElementById(_id).style.display = _val;
}
else {
if (document.layers) {
if(!previousDisplay[_id]){
previousDisplay[_id] = document._id.display;
}
document._id.display = _val;
}
else {
if(!previousDisplay[_id]){
previousDisplay[_id] = document.all._id.style.display;
}
document.all._id.style.display = _val;
}
}
}
function hide(_id) {
sh(_id, 'none');
}
function show(_id) {
var style = previousDisplay[_id];
if(!style){
style = 'block';
}
sh(_id, style );
}
Related
I want to check if the state of show to change the innerText of the button according to it but when I run it the else statment doesnt work
let showBtn = document.querySelector('.show-more');
showBtn.onclick = function () {
let show = false;
if (show === false) {
showBtn.innerText = 'Show Less';
show = true;
} else {
showBtn.innerText = 'Show more';
}
}
showBtn is false on each click in your code. It should not be assigned in the onclick handler. Try this:
let showBtn = document.querySelector('.show-more');
let show = false;
showBtn.onclick = function() {
if (show === false) {
showBtn.innerText = 'Show Less';
} else {
showBtn.innerText = 'Show more';
}
show = !show;
}
<button class="show-more" />Show</button>
Reset the value of show, every click by this way.
let showBtn = document.querySelector('.show-more');
show = false;
showBtn.onclick = function () {
if (show === false) {
showBtn.textContent= 'Show Less';
show = true;
} else {
show = false
showBtn.textContent= 'Show more';
}
}
You should not even be using a variable here in the first place. The accepted answer just creates a new bug as it will break as soon as you have more then one element as the global state would apply to all the elements.
If you want to attach state to elements you can either do it by adding/removing classes or through data attributes (or whatever more specific attribute is applicable).
let showBtn = document.querySelector('.show-more');
showBtn.onclick = function (event) {
// event.target is the clicked element
if (event.target.matches('.expanded')) {
showBtn.textContent= 'Show Less';
else {
showBtn.textContent= 'Show more';
}
event.target.classList.toggle('expanded')
}
In this example the class 'expanded' is used to keep track of the state of the button. This also lets you attach different visual "states" through CSS.
In this case do not assign your state variable let show inside of the calling function. When you do that it will initialize the variable every time you call it. This causes a performance issue (see variable initialization and garbage collection) and depending on what you want to do it will break.
Someone here as already given an answer, but in their answer the variable declaration is in global scope. Most people agree that it's not a good idea to declare global variables, especially with such a general name as show . Later on, as your code base grows, you're likely to run into conflicts and your code will start acting in ways you can't predict. This is probably the most universally agreed upon coding convention. It's a bad habit. Learn how to do it the right way now.
These two StackOverflow answers contain examples that are a good starting point to producing working modular code to control the state of your objects:
wrapper function: https://stackoverflow.com/a/50137216/1977609
This is another way to implement your button: https://stackoverflow.com/a/10452789/1977609
I am a beginner coder and I'm trying to change the background color of a div based on how far down scrolled the webpage is, where am I going wrong?
Do I need to put in something to call the scrollTop amount?
(function () {
var scroll = .scrollTop;
if (scroll > 50) {
document.getElementByClassName("shop").style.backgroundColor = '#99C262';
}
else
{
document.getElementByClassName("shop").style.backgroundColor = ‘red’;
}
})();
Lose the dot, instead of “.shop” go for “shop”
And the actual function getElementsByClassName and it returns a collections of divs with the class name. But you need the first one (assuming you have only one such div) hence the 0 index in array
parentDOM.getElementsByClassName('test')[0].style.backgroundColor = "red";
<p class="test">hello here</p>
Many errors in the code....
var scrole = .scrollTop; not sure if you are trying to assign any value or is it window.scrollTop.
document.getElementByClassName(".shop") should be changed to document.getElementByClassName("shop")
else if (scroll < 50 ){ //statement } to be changed to else { //statement }
function is wrapped in small bracket but has never been invoked.
Self invoking function example :-
(function(){
console.log(Math.PI);
})();
Using a dot before a class name when getting it in javascript using getElementsByClassName is an Incorrect Syntax. Below is the correct syntax.
document.getElementsByClassName("shop")
Tip: Always Use the console window to monitor your Syntax and other errors.
Your code are only executed once if you don't attach a listener. Let me just use these code from MDN docs with a bit of edit. The docs
let last_known_scroll_position = 0;
let ticking = false;
function doSomething(scroll_pos) {
if (scroll_pos > 50) {
document.querySelector(“.shop”).style.backgroundColor = '#99C262';
} else if (scroll_post < 50) {
document.querySelecttor(“.shop”).style.backgroundColor = ‘red’;
} else {
// add more colorrrs!
}
}
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
ticking = true;
}
});
I am trying to write a simple toggle function in Javascript. What it does is take an element, a style name, and a desired value. If the current value of that style on the element is the empty string, that means it hasn't been set, so we set it to the given value. Otherwise, set it to the empty string to disable it.
My code is below:
function toggleStyle(el, styleName, value) {
if (el.styleName === '')
{
el.styleName = value;
}
else
{
el.styleName = '';
}
}
However, I'm unsure how I call this function if I want to toggle the visbility of a box. I know to directly change the visibility: I would normally do:
var box = document.getElementById("box");
box.style.display = "none";
But how would I call my toggleStyle to do this? I've tried writing:
toggleStyle (box, display, "none");
toggleStyle (box, style.display, "none");
toggleStyle (box.style, display, "none");
but nothing seems to work.
bracket notation is what you need and you need to pass strings.
function toggleStyle(el, styleName, value) {
if (el.style[styleName] !== value) { //better to check that it is not the value you have
el.style[styleName] = value;
} else {
el.style[styleName] = '';
}
}
var btn = document.querySelector("button")
var div = document.querySelector("#foo")
btn.addEventListener("click", function () {
toggleStyle(div, "display", "none")
});
<button type="button">Click Me</button>
<div id="foo">FOO</div>
Where would this fail? Color codes are one thing, but this is the basic step in the right direction.
You should write it like this instead:
function toggleProp(obj, prop, value){
obj[prop] = obj[prop] ? "" : value;
}
toggleProp(box.style, "display", "none");
You should also learn how to use the debugger:
From this we can see that it was because the variable display is not defined before using it.
Two things:
First, change your toggleStyle function so that it modifies the element's style property directly, and use bracket notation to dynamically access the property element of the style object:
function toggleStyle(el, styleName, value) {
if (el.style[styleName] === '') {
el.style[styleName] = value;
} else {
el.style[styleName] = '';
}
}
Second, pass a string of the style property when you use toggleStyle:
toggleStyle(box, "display", "none"); // display needs to be in quotes
I have a flip toggle button().I am writing a function on change of toggle button,on change I am declaring js confirm box ,if confirms true the button remains in changed state,else it will revert in its previous state.My issue is the function is getting iterating(looping).Please suggest
To me it looks quite ok. Maybe you just forgot to encapsulate your code in $(document).ready - this is necessary because otherwise your Javascript function will be loaded before the HTML DOM has been loaded - so your function will fail to access the DOM elements.
$(document).ready(function() {
$("#btn").on("change", function() {
var txt;
var btnStatus = $("#btn").val();
console.log("btnstataus>>>>>" + btnStatus);
var r = confirm("Are you sure to change?");
if (r == true) {
if (btnStatus == "on") {
$("#btn").val("on");
} else {
$("#btn").val("off");
}
} else {
if (btnStatus == "on") {
$("#btn").val("off");
} else {
$("#btn").val("on");
}
}
});
});
Here is a working sample of your code:
https://plnkr.co/edit/AdzcN04F1fsLe9xw454j?p=preview
I would like to be able to check if a checkbox has been checked against a value in local storage. If it is checked I would like to apply a background colour to a part of the page.
Page to apply CSS http://upskillapps.com/resources/1.png
My local storage data looks like the following:
Local storage data http://upskillapps.com/resources/2.png
If the completion checkbox is active I would like to apply a green background and if not an orange background.
I have the following code so far but am new to JS and so it needs a lot of work:
function highlightComplete() {
if (DevPlan.completion == 'true') {
info-row.addClass('background-green');
} else if (DevPlan.completion == 'false') {
info-row.addClass('background-orange');
}
}
Any help would be greatly appreciated.
Here's an example for you:
$(document).ready(function () {
//this function executes on page load
if (!localStorage.getItem('color')) { //if our value does not already exist, we'll default it to green
localStorage.setItem('color', 'green');
$('#div').addClass('green');
} else { //our value exists already
if (localStorage.getItem('color') == 'green') {
$('#div').addClass('green');
} else {
$('#div').addClass('red');
}
}
});
$('button').click(function () {
var color = localStorage.getItem('color');
if (color == 'green') {
$('#div').removeClass().addClass('red');
color = 'red';
} else {
$('#div').removeClass().addClass('green');
color = 'green';
}
localStorage.setItem('color', color);
});
Basically, the idea here is to check for the value on page load and set your CSS based on that, then wait for user input to change the value and CSS together.
Here's what this code looks like in action: http://output.jsbin.com/yexahatoye
Thank you very much Michael Parker for your help.
I now have a solution after fiddling about for a while and learning a lot in the process:
for (var i = 0; i < devPlan.length; i++) {
var item = devPlan[i].tables.completion[0].active;
if (item == true) {
$('#' + i).find('.info-row').addClass('background-green');
}
else {
$('#' + i).find('.info-row').addClass('background-amber');
}
}
To apply the CSS I have used the table row ID to apply the CSS. Hopefully it helps someone else.