I am trying to make a div
, or a p
element visible by a click of a button. Something like this in JavaScript:
document.getElementById("id").style.transition="visibility";
document.getElementById("id").style.visibility="visible";
Is this possible? Or am I just doing it wrong?
Assuming you want to use a transition to fade an element in, one approach is to use CSS (which can take advantage of hardware acceleration to offload the redraw to the GPU, if it's available).
To do this we can simply specify a CSS animation to run on all elements to be added, since I'm adding all elements to the same container element this can be achieved with the following:
#container * {
/* Webkit 35: */
-webkit-animation: fadeIn 1s linear;
/* Firefox 28, Opera 22, IE 11: */
animation: fadeIn 1s linear;
}
On loading the page, the specified animation will run; the animation being:
/* defining an animation '@keyframes', naming the animation 'fadeIn': */
@keyframes fadeIn {
/* the starting point: */
from {
/* the starting property and property-value: */
opacity: 0;
}
/* the finishing point: */
to {
/* the finishing property and property-value: */
opacity: 1;
}
}
(The -webkit-prefixed version is in the linked demo, and is exactly the same except for the first few characters, which contain the vendor-prefixed @-webkit-keyframes
).
To add the elements we use the, almost entirely arbitrary, JavaScript:
function createElem () {
// gets the value of the first 'select' element contained within
// a 'label' element:
var elemType = document.querySelector('label select').value.toLowerCase(),
// creates a new element, and retains a reference to that
// created-element:
elem = document.createElement(elemType);
switch (elemType) {
// if we created an 'input' or a 'textarea'
case 'input':
case 'textarea':
// we set the value property of that element to the string:
elem.value = 'created a new ' + elemType + ' element.';
break;
// if we created an 'img' element:
case 'img':
// we set the 'alt' property:
elem.alt = 'created a new ' + elemType + ' element.';
break;
// otherwise we assume the default is true,
default:
// and we set the textContent of the element:
elem.textContent = 'created a new ' + elemType + ' element.';
break;
}
// in all cases we set the 'title' property:
elem.title = 'created a new ' + elemType + ' element.';
// and we add the created-element to the element with the 'id' of
// 'container'
document.getElementById('container').appendChild(elem);
}
// add a 'click' event-handling function to the (first) 'button' element:
document.querySelector('button').addEventListener('click', createElem);
References: