I want to hide tags with a specific id or class using javascript. I have kept a single ID and CLASS for every span tag called "ch"(adding different ID and CLASS to each span is very difficult for me)
I have a checkbox which will toggle the visibility of the .
Now here's the problem:
- I click the checkbox once, everything hides fine
- Click it the second time(to show the again), all the content in the tag goes to the left of the screen.
- Click it again and everything goes berserk
I want the code to show/hide the span tags when clicked and when the spans are hidden, I don't want that line to remain there. I want that entire line to be removed, and when it's set for visible again, I want these lines to reappear. I hope someone can help me. Below is the code:
function sh_chords() {
tmp_log += "sh_c|";
var b = document.getElementById("showing_chords").checked;
for (i = 1; i <= lcnt; i++) {
el = document.getElementById("ch");
try {
if (!b) {
el.style.color = "black";
el.style.cursor = "default";
$(".ch").hide();
} else {
el.style.color = "#0000FF";
el.style.cursor = "pointer"
$(".ch").show();
}
} catch (d) {}
}
}
Since you are using jquery, you can use it's helper function which is specifically for toggling visibility.
$('.ch').toggle( $('#showing_chords').prop('checked') );
Related
Using this script to open 1 of multiple menus based on the target ID. The class is .dropdownDiv. The script starts by removing the "show" class from any .dropdownDiv's, then allowing the user to toggle the targeted .dropdownDiv.
The issue is, the .remove and .toggle don't appear to work together. They work individually just fine. I can toggle one div show-unshow all day long, but clicking the other buttons will not control it. I can do the reverse and have one button remove the div from another, but then the targeting button will not remove it's own div.
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(event) {
var divs = document.querySelectorAll('.navButton');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', showDropDown);
}
});
function showDropDown() {
//un-show all dropdowns
var containers = document.querySelectorAll('.dropdownDiv');
for (var i = 0; i < containers.length; i++) {
containers[i].classList.remove('show');
}
// show targeted dropdown only
var d = document.getElementById(event.target.dataset.target);
d.classList.toggle("show");
console.log(d);
}
</script>
a trivial way to toggle something, that is using a flag and flip it each time you hit an action, so you can do something like so:
if(a)
{//something to do}
else
{// another action to do}
a = ! a;
so, you can remove the clicked drop down instead of removing all drop down classes.
I have a simple form (text field and submit button). I am trying to have the user submit a number, and the resulting number will display one div (from a set of divs).
I tried using this example as a base (when the user clicks a link, it shows a div, but hides others).
My test is below:
var divState = {};
function showhide(oFrm) {
var dividnum = oFrm.Inputed.value;
var prepar = "para";
var divid = prepar + theInput; /* should result in something like "para52" */
divState[divid] = (divState[divid]) ? false : true;
//close others
for (var div in divState){
if (divState[div] && div != divid){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
http://jsfiddle.net/LfzYc/431/
Note: I am NOT proficient in JavaScript at all, which is why I am having difficulty.
Also, I'd like to add a function ... if the number entered is not between 1-4, show a different div, maybe with the id paraEnd.
Please look at the jsFiddle based on your one. I hope I've done what you want. I changed the showhide function and your HTML (fixed div's IDs and added one more div#paraEnd). I'd suggest you refactoring your code.
You should use jQuery to have an easy way to manipulate the DOM.
Using jQuery I made an example for you, just change your JS and paste mine:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
// get the paragraphs
var paragraphs = $('.paragraph');
// form submit
$('#paragraphform').submit(function (e) {
// prevent the event to flow
e.preventDefault();
// get the input value
var value = $('#Inputed').val() - 1;
// reset all divs removing active css class
paragraphs.removeClass('active');
$('.error').removeClass('active');
// verify if the value doens't exist
if(value < 0 || value > paragraphs.length - 1) {
$('.error').addClass('active');
return;
}
// show the active div
paragraphs.eq(value).addClass('active');
});
})(jQuery);
</script>
Is that what you need?
If you not familiar with jQuery, this is the jquery Learn Center:
https://learn.jquery.com/
And this is a nice tutorial for beginners:
http://www.tutorialspoint.com/jquery/
Im trying to hide/show a JS function I have defined in a chrome extension.
What I have so far:
The span classes I am trying to hide are label:
dspan.className = "cExtension";
//Create toggle button:
function createToggleButton(){
var toggleButton = document.createElement("button");
toggleButton.innerHTML = "Toggle Overlay";
toggleButton.id = "Toggle"
var header = document.getElementById("header");
header.appendChild(toggleButton);
toggleExtension();
}
// find all spans and toggle display:
function toggleExtension(){
var spans = document.getElementsByTagName('span');
var toggle = function() {
for (var i = 0, l = spans.length; i < l; i++) {
if (spans[i].getAttribute('class') == 'cExtension')
if (spans[i].style.display == 'none') spans[i].style.display = '';
else spans[i].style.display = 'none';
}
}
document.getElementById('Toggle').onclick = toggle;
}
The button shows on the header, however it is unclickable. If I change document.getElementById('Toggle').onclick = toggle; to document.getElementById('Toggle').onclick = alert{"Hello"); the alert is triggered on page load on not onclick. I am trying to get this done in pure JS. Where am I going wrong?
First of all, document.getElementById("Toggle").onclick = alert("Hello"); will set the onclick event to whatever the alert function returns, not the alert function itself. So the alert function happens at page load so it can figure out what to return. So you could do this: document.getElementById("Toggle").onclick = function(){alert("Hello");}; and that might work.
Edit: Scratch everything that was here: I missed that toggle variable set to a function in toggleExtension.
I haven't tested all this so I can't guarantee that it'll all work in your specific case.
if visible is set remove it, otherwise add it
div.classList.toggle("visible");
add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );
Make sure browser support: http://caniuse.com/#feat=classlist
Why not use jQuery?
It will do all hard job for you.
http://api.jquery.com/toggle/
Cheers!
I have a function that loops through all of the inputs of my form and checks if they are filled or not. If the field is blank, it makes that specific input pink and returns false.
I'm trying to add a "Field Required" message underneath the inputs that are not filled. So i coded an extra table row after each one, with a div that holds the error message. The css for the div is set to "display:none" on page load.
Right now my function is showing "required" for every input and not just the ones that are blank, but the pink coloring is still working correctly.
How do I get the "required" div to show and hide correctly like the pink coloring does?
checkinputs = function (blockOne,blockTwo) {
inputGood = true;
blOne = $(blockOne);
blTwo = $(blockTwo);
blInput = [blOne,blTwo];
for (x = 0; x < 2; x++) {
var validators = blInput[x].find(" [id$='RequiredIndicator']").parent().parent('tr').find(':input:not(:hidden)');
var notAllFilled = validators.filter(function(){
var myInput = $(this); //.parent().parent('tr').find(':input');
var filledVal = myInput.val();
var isFilled = $.trim(filledVal).length;
if (isFilled) {
$(this).css('background-color', 'white');
$(this).closest('div').find('.required').hide();
$(this).parent('td').prev('td').find('span').text('*');
}
else {
$(this).css('background-color', 'pink');
$(this).closest('div').find('.required').show();
$(this).parent('td').prev('td').find('span').text('*');
inputGood = false;
}
return isFilled;
}).length;
var inputCount = validators.length;
};
if( !inputGood ){
$('#errorAlert').append('<span style="font-weight:bold;">"Some required information is missing. Please complete the missing fields below."</span>' + '<br><br>');
$('#errorAlertTwo').append('<span style="font-weight:bold;">"Some required credit card information is missing. Please complete the missing fields below."</span>' + '<br><br>');
}
return inputGood;
};
HERE IS A FIDDLE OF THE ISSUE:
http://jsfiddle.net/RNMM7/
Your issue is almost definitely your line to show the div:
$(this).closest('div').find('.required').show();
What this line does is:
Starting at your $(this), it finds the nearest ancestor [including $(this)] that is a div, going up the DOM tree
Finds all elements with class 'required' under that div, and shows them.
Without seeing how your HTML is structured, my guess is that the nearest div element up the DOM tree encompasses all your .required elements. You'd need to replace the 'div' in that statement with an element lower in the DOM tree that would only encompass your $(this) and the one .required element you want to show.
I have multiple JavaScript draggable DIV windows. When clicking a DIV, I want the window to get the highest z-index value. I've made a solution by adding/removing classes to the element in focus, BUT, I would like the windows to keep their "layer" -order (as if the entire DIV window node was re-appended to the DOM when being clicked).
Let's say there are five DIV's in the DOM. div1, div2, div3, div4 and div5. -div5 is closest to the front and div1 is in the back and so on.
When clicking div1, -div1 will get focus and put to front, setting div5 back one step. Then clicking div3, -div3 gets closest to front and div1 and div5 are put back one step like this: div2, div4, div5, div1, div3.
If you don't want to loop through all your divs and don't want to mess up with z-index you can just append again that div to the parent element (the body?) before dragging.
function stepUpNode(elementDragged){
var parentNode = elementDragged.parentNode;
parentNode.appendChild(elementDragged);
}
If you'd like to do this without re-appending the element, my solution when I wrote something similar a while back was to keep track of the maximum z-index. Every time a window is brought forward, the maximum z-index is incremented and the element's z-index is set to the new value. Of course, if someone messes with the windows enough, they might end up having very large z-index values, so this isn't always the best solution.
var maximumZIndex = 1;
var bringForward = function (element) {
maximumZIndex += 1;
element.style.zIndex = maximumZIndex;
}
The first and most likely easiest approach: simply increase the maximum z-index every time a div gets selected. Since the z-index value can become pretty large (2147483647 if I remember correctly) you most likely will never run out of levels...
The following snippets use some jQuery:
var frontmostWindow = null;
var topZIndex = 10;
$('div').click(function() {
if (this != frontmostWindow) {
frontmostWindow = this;
topZIndex++;
$(this).css('zLevel', topZIndex);
// anything else needed to acticate your div
// ...
}
});
If you have restrictions on the z-indices you can use, you will need to re-assign levels every time a different div gets selected, e.g. like this:
// store z-index-ordered divs in an array
var divs = $('div').toArray().sort(function(a, b) {
return parseInt($(a).css('zIndex'), 10) - parseInt($(b).css('zIndex'), 10);
});
// store available z-indices
var zIndices = [];
for (var i = 0; i < divs.length; ++i) {
zIndices.push($(divs[i]).css('zIndex'));
}
// Event listener for clicks
$('div').click(function() {
alert("heyya " + this.id);
var element = this;
var index = divs.indexOf(element);
// check if clicked element is not already the frontmost
if (index < divs.length - 1) {
// remove div from array and insert again at end
divs.splice(index, 1);
divs.push(this);
// re-assign stored z-indices for new div order
for (var i = 0; i < divs.length; ++i) {
$(divs[i]).css('zIndex', zIndices[i]);
}
// anything else needed to acticate your div
// ...
}
});