I have a list of paragraphs in a chatbox:
<div id=chatbox>
<p><i>15:21</i><b data-c=john>john</b>: hello jack</p>
<p><i>15:22</i>i want to tell you something</p>
<p><i>17:17</i><b data-c=jack>jack</b>: hi john.</p>
<p class=hidden><i>20:15</i>Ο <span data-c=server>server</span> alex joined the chat</p>
<p><i>17:17</i><b data-c=alex>alex</b>: hi all of you.</p>
</div>
and I want to have a toggle button in order to show/hide the hidden elements. Is there a way to toggle the style of hidden class from display:none to display:inline and backwards?
Notice that if i change all existing class=hidden to visible, when AJAX brings a new hidden line, it will still be hidden in contrast with previous elements. Is there a way to change the content of a class style?
It's a really bad idea to make javascript iterate through all of the elements to change the display when you can do it really easily by just toggling a class on a parent element.
Here's the codepen demo
When the button is clicked, you can just toggle a showHidden class on the #chatbox element, and use CSS to hide or display all of the hidden items inside it.
CSS:
.hidden {
display: none;
}
#chatbox.showHidden .hidden {
display: inline;
}
jQuery:
$(document).ready( function() {
$('.toggleButton').on('click', function(){
$('#chatbox').toggleClass('showHidden');
});
});
Add a button
<div id=chatbox>
<p><i>15:21</i><b data-c=john>john</b>: hello jack</p>
<p><i>15:22</i>i want to tell you something</p>
<p><i>17:17</i><b data-c=jack>jack</b>: hi john.</p>
<p class=hidden><i>20:15</i>Ο <span data-c=server>server</span> alex joined the chat</p>
<p><i>17:17</i><b data-c=alex>alex</b>: hi all of you.</p>
</div>
<button id="show_hidden">Show Hidden</button>
change the style for that class, and any future elements with that class
var button = document.getElementById('show_hidden'),
hidden = true;
button.addEventListener('click', function() {
var st = document.getElementById('myStyle');
if (st) {
st.innerHTML = '.hidden { display: '+ (hidden?'block':'none') +'; }';
}else{
var css = '.hidden { display: block; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
style.id = 'myStyle';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
button.innerHTML = (hidden ? 'Hide' : 'Show');
hidden = !hidden;
}, false);
FIDDLE
if using jquery look up .toggle here http://api.jquery.com/toggle/
also see here for javascript only answer: Jquery .toggle replacement code
Related
This is hard to explain precisely. But here we go:
I have a button that calls a function
<button onclick="myFunction_gsm()">Men</button>
When the button is pressed, it triggers a script. This script grabs a hidden section and displays it. The script goes like this:
<script>
//Gender Selection Script Men//
function myFunction_gsm() {
var x = document.getElementById("men-sizing");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
On the screen this plays out so that you click the button, a section appears, if I click the same button again the section hides again. However, I have another 2 sections. 3 Sections in total. For this example, the above script works for 1 section, the A section. There is also B and C. I would like to include the behavior that when A has been pressed, therefore displaying section A, if I then press the button for B the B section appears but the A section disappears without having to press the A button again. A Dynamic change of sorts.
I am a complete starter for coding but I assume it's something you add into the if statement. Any help would be greatly appreciated.
I would prefer solutions that incorporate the code I have now, since I won't have much use recreating it from scratch. It would solve this, but cause many new problems.
Define a class for all sections, for example sec. On click event pass the selected id, hide all of them and just toggle the selected one.
function myFunction_gsm(sectionId) {
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
if(itm.id !== sectionId) itm.style.display = 'none'
})
var x = document.getElementById(sectionId);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
itm.style.display = 'none'
})
<button onclick="myFunction_gsm('sec1')">Sec1</button>
<button onclick="myFunction_gsm('sec2')">Sec2</button>
<button onclick="myFunction_gsm('sec3')">Sec3</button>
<div class="sec" id="sec1"> some text 1 here</div>
<div class="sec" id="sec2"> some text 2 here</div>
<div class="sec" id="sec3"> some text 3 here</div>
You might use class names for the sections. Then at the start of the function have all elements with that class name be hidden and afterwards display the currently clicked one.
If you want to preserve the toggle functionality for the section (so clicking A twice displays and hides it again), you want to check the display state of the currently clicked one first before hiding all. And then only display the clicked one if it was hidden before.
The modern approach is to avoid using .style within JS. This add the stylign as inline-style which ahs the highest specificty weight with exeption of important. The modern solution is to use classList to apply, remove or toggle a CSS-Class.
You add a class to CSS to hide element such as: .display-none { display: none; }`
Then you add a function to your button to hide all sections with a certain class by adding the class mentioned at step 1: function hideAll() { document.querySelectorAll('.class-name').forEach(el => el.classList.add('display-none')); }
You add a second function to the onclick trigger of a button thow a certain element by removing the class: element.classList.remove('display-none');
function hideAll() {
document.querySelectorAll('.section').forEach(el => el.classList.add('display-none'));
}
function showA() {
document.querySelector('#section-a').classList.remove('display-none');
}
function showB() {
document.querySelector('#section-b').classList.remove('display-none');
}
function showC() {
document.querySelector('#section-c').classList.remove('display-none');
}
.display-none {
display: none;
}
<button onclick="hideAll(); showA()">Show A</button>
<button onclick="hideAll(); showB()">Show B</button>
<button onclick="hideAll(); showC()">Show C</button>
<section id="section-a" class="section display-none">Section A</section>
<section id="section-b" class="section display-none">Section B</section>
<section id="section-c" class="section display-none">Section C</section>
CSS-only Solution
If you dont want to sue scripts, you could use a pure CSS-Method that works through the :target selector. This allows you to use anchor as "trigger".
Hide the scetiond with display: none; either by selecting them directly or adding a class to them.
use an anchor with an href="#id" instead of a link. This will move the page to that element but also manipulate the websites adress.
Use *:target { display: block; } to show targeted elements:
.display-none {
display: none;
}
*:target {
display: block;
}
/* for styling purpose only */
a {
margin-right: 15px;
}
Show A
Show B
Show C
<section id="section-a" class="display-none">Section A</section>
<section id="section-b" class="display-none">Section B</section>
<section id="section-c" class="display-none">Section C</section>
I'd like to implement some javascript that uses an if statement to change some css styles. Not sure how to do it, any help would be great!
If you want to change a single style of an element using JavaScript, use
document.getElementById(id).style.property = new style
eg :
document.getElementById("myDiv").style.color= "red";
To add a new CSS class to an element, use
document.getElementById(id).classList.add("mystyle");
To remove
document.getElementById(id).classList.remove("mystyle");
Demo :
function changeSingleStyle() {
var color = document.getElementById("myDiv").style.color;
if (color === "red")
document.getElementById("myDiv").style.color = "yellow";
else
document.getElementById("myDiv").style.color = "red";
}
function addClass() {
document.getElementById("myDiv").classList.add("mystyle");
}
function removeClass() {
document.getElementById("myDiv").classList.remove("mystyle");
}
.mystyle {
color : red;
background: green;
font-size: 50px;
}
<div id="myDiv"> This is a div </div>
<button onclick="changeSingleStyle()">changeSingleStyle</button>
<button onclick="addClass()">addClass</button>
<button onclick="removeClass()">removeClass</button>
First of all, to change CSS using JavaScript, the syntax looks like the following:
document.getElementById(id).style.property = new style
For example, if you want to change the display property of an element with id = "container" to block, it would be:
document.getElementById("container").style.display = "block";
Given this, you could easily add an IF statement depending on what condition you want. For example:
if(condition)
{
document.getElementById("container").style.display = "block";
}
You can do this with .style.property or .style.cssText
function myStyleFunction() {
document.getElementById('styled').style.color = 'red';
}
function myStyleFunctionCssText() {
document.getElementById('styled2').style.cssText = 'color: lime';
}
<button onclick="myStyleFunction();" id="styled">
Style with .style.color
</button>
<button onclick="myStyleFunctionCssText();" id="styled2">
Style with .style.cssText
</button>
With this code, the button on the left will go red, the one on the right will go lime.
You can also do this easily with jQuery.
function myStyleFunction() {
$(".style").css("color", "magenta");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="style" onclick="myStyleFunction();">Style by class</button>
<button class="style">Style by class 2</button>
This code changes all elements in the classes color to magenta if you click the first button.
function barHtml (percent) {
return `
<div class= "${percent>25 ? "class1":" class2"}"
style="width: ${percent}%;">
</div>`
}
document.body.innerHTML=<div>${barHtml(20)}</div>
I would like to "close" a modal window. It's a wordpress template and it's ugly...
I have a div :
<div class="modal">
<section style="position:relative;z-index:10;">
<div style="margin-bottom: -50px; margin-right: 50px; text-align: right;">
<img src="./wp-content/img.png" alt="Close">
</div>
<p><img src="./wp-content/img2.png" alt="test"></p>
</section>
</div>
And when the img with alt="Close" is clicked, I would like to close or set the opacity of all the div.modal at 0. Is it possible with JS?
jQuery
$('img[alt*=Close]').click(function() {
$('.modal').hide();
});
JS
var img = document.querySelector('img[alt*=Close]'),
modal = document.querySelector('.modal');
img.addEventListener('click', function() {
modal.style.display = 'none';
});
when the img with alt="Close" is clicked, I would like to close or set the opacity of all the div.modal at 0.
Absolutely!
First i want to mention that there is some attribute selectors which are now officially available in css3, so that can be used as a jQuery selector like:
$('body').on('click', 'img[alt="Close"]', function(e){
$(this).closest('.modal').fadeOut(); // to fade out the entire div.
// $(this).closest('.modal').hide(); // hide will hide the modal
});
If your modal is dynamically created then you have to follow the technique of event delegation, which has the syntax like:
$(staticParent).on(event, selector, callback);
Yep! Just set thee css property opacity
$(".modal").css({ opacity: 0.5 });
You can listen for click events on the img div with:
document.querySelector("img[alt=Close]").addEventListener("click", yourHandler);
However, accessing an image using its alt attributes looks like a terrible idea. alt is to display infotip and accessibility message for the user, not to identify a DOM element.
It would much better if you can give this image an id or a class:
document.getElementById("yourImgId").addEventListener("click", yourHandler);
Then:
var modal = document.querySelector(".modal");
function yourHandler(){
modal.style.opacity = 0;
}
or
function yourHandler(){
modal.style.display = "none";
}
A last solution can be to define the style properties in a stylesheet like:
.modal.disabled {
display: none;
}
And then add the class to modal to disable it.
function yourHandler(){
modal.classList.add("disabled");
}
This last solution is more flexible and easier to maintain as it separates the logic to the style.
How can I make a button change its position after being clicked like this demo here but instead of the active parameter I would like it to be at margin-left:50px; definitely after clicked
HTML
<div class="button">
<button type="fb-like">Fb-Like</button>
</div>
CSS
.button:active {
margin-left:50px;
}
/* But with a on clicked parameter instead of active */
You need to use JavaScript:
var d = document.getElementById("button");
d.addEventListener('click',function(){
d.className = d.className + " move";
});
Demo: http://jsfiddle.net/LJHQW/3/
Or, if you're already using jQuery:
$('.button').click(function(){
$(this).addClass('move');
});
Demo: http://jsfiddle.net/LJHQW/1/
Here's a simple solution:
http://jsfiddle.net/LJHQW/2/
JavaScript:
/* Toggles the style class on click */
$("button").click(function() {
$(".button").toggleClass("buttonLeft");
});
CSS:
.buttonLeft {margin-left:50px;} /* But with a on clicked parameter instead of active */
I am attempting a simple drop down menu using Javascript but when I hover over my link that should display my drop down menu nothing happens. What do you think is wrong with my Javascript?
Javascript:
function onHover( divID )
{
var div = document.getElementByID( divID );
if (div)
{
div.className = "unHidden";
}
}
function onLeave( divID )
{
var div = document.getElementByID( divID );
if (div)
{
div.className = "hidden";
}
}
My css:
.hidden { visibility: hidden; }
.unHidden { visibility: visible; z-index: 30; }
And finally my HTML:
<li>
<a onmouseover="onHover('otherLinks)" onmouseout="onLeave('otherLinks')">Other Links</a>
<div class="hidden" id="otherLinks" onmouseover="onHover('otherLinks)" onmouseout="onLeave('otherLinks')">
<ul>
<li>Events</li>
<li>Food & Nutrition</li>
<li>FAQ</li>
</ul>
</div>
</li>
Is there any reason why you're using Javascript for your drop downs and not HTML and CSS?
Son of suckerfish drop downs is a good place to start for a HTML and CSS drop down option: http://htmldog.com/articles/suckerfish/dropdowns/
It is document.getElementById( divID );, note that it is "Id" not "ID". You are also missing a single quote, it should be onmouseover="onHover('otherLinks')". I also agree with Dan's answer.
May be this is the issue:
You have passed the div name like
onmouseover="onHover('otherLinks)"
Try to give the div name like
onmouseover="onHover('otherLinks')"
or try java script ddl
You can only use css. Or use the library JQuery.