if var > then div display: none - javascript

I have a variable lineNum that increment when I click on h1
I am trying to make 'if' make a div display:none, but I just cant type the if code right?
Here is the if JQuery line I am having trouble with below:
if (lineNum > 1) {blue-sun-div, display: none;}
thank you for your help : )
***EDIT:
hello
here is the jquery code I have made ( my first jquery coding project)
Two divs move across the screen when I click 'h1'and 'h2', 'var' also increments. When 'var' goes 1 or above: blue-sun-div should disappear.
I can make the blue-sun-div disapear if I refresh the browser but only whilst i manually enter 'var' =1 or more ,so I have the div-name correct, but it will not disappear when lineNum++ raises the var 'lineNum' past 1 automatically.
Do I need to re trigger the code at the end, after lineNum does its job?
sorry if this does not make sense. its 4am here.
here is the code. thank you very much
$(document).ready(function() {
var lineNum = 0;
$("h1").click(function() {
$("#blue-sun-div, #red-sun-div").animate({
"left": "+=200px"
}, 1000);
});
$("h2").click(function() {
$("#blue-sun-div, #red-sun-div").animate({
"left": "-=200px"
}, 1000);
});
lineNum++;
if(lineNum > 1) {
$("#blue-sun-div").css({ display: "none" });
}
})

To make an element have css display: none, you can use the following method:
Pure JavaScript:
if(lineNum > 1) {
document.getElementById("blue-sun-div").style.display = "none";
}
With JQuery (I recommend this)
if(lineNum > 1) {
$("#blue-sun-div").css({ display: "none" });
}
This is assuming you have a <div id="blue-sun-div"> ....

just do:
if blue-sun-div is a classname
if(lineNum>1){
$(".blue-sun-div").hide();
}
if blue-sun-div is an ID
if(lineNum>1){
$("#blue-sun-div").hide();
}

do you have access to jquery? or are you just using plain javascript?
the easiest way would be:
if(lineNum > 1)
{
$('#blue-sun-div').hide();
}
this assumes that you have jquery setup already and that blue-sun-div is the id of the div (<div id="blue-sun-div">)
if it is the class (<div class="blue-sun-div">) then the jquery above needs to change to $('.blue-sun-div').hide();
for plain javascript, the best way would be to create a hide function and call it in the onclick of the h1.
in your javascript:
function hideDiv(divId){
document.getElementById(divId).style.display="none";
}
then in the html:
<h1 id="SomeID" onclick="hideDiv('blue-sun-div');">H1 TEXT</h1>

Related

For loop with eval not working

My first time writing my own javascript/jQuery for-loop and I'm running into trouble.
Basically, I have a series of divs which are empty, but when a button is clicked, the divs turn into input fields for the user. The input fields are there at the outset, but I'm using CSS to hide them and using JS/jQuery to evaluate the css property and make them visible/hide upon a button click.
I can do this fine by putting an id tag on each of the 7 input fields and writing out the jQuery by hand, like this:
$('#tryBTN').click(function(){
if ( $('#password').css('visibility') == 'hidden' )
$('#password').css('visibility','visible');
else
$('#password').css('visibility','hidden');
}
Copy/pasting that code 7 times and just swapping out the div IDs works great, however, being more efficient, I know there's a way to put this in a for-loop.
Writing this code as a test, it worked on the first one just fine:
$('#tryBTN').click(function() {
for(i = 1; i <= 7; i++) {
if($('#input1').css('visibility') == 'hidden')
$('#input1').css('visibility', 'visible');
}
});
But again, this only works for the one id. So I changed all the HTML id tags from unique ones to like id="intput1" - all the way out to seven so that I could iterate over the tags with an eval. I came up with this:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
if ($(eval('input' + i)).css('visibility') == 'hidden')
$('input' + i).css('visibility', 'visible');
}
});
When I put in the eval stuff - it doesn't work. Not sure what I'm doing wrong. A sample of the HTML looks like this:
<form>
<div class="form-group">
<label for="page">Description: Specifies page to return if paging is selected. Defaults to no paging.</label>
<input type="text" class="form-control" id="input7" aria-describedby="page">
</div>
</form>
You were forgetting the #:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
var el = $('#input' + i); // <-- The needed `#`
if (el.css('visibility') == 'hidden') {
el.css('visibility', 'visible');
}
}
});
#Intervalia's answer explains the simple error in your code (the missing #), and the comments explain why you should never use eval() unless you absolutely know it's the right tool for the job - which is very rare.
I would like to add a suggestion that will simplify your code and make it more reliable.
Instead of manually setting sequential IDs on each of your input elements, I suggest giving them all a common class. Then you can let jQuery loop through them and you won't have to worry about updating the 7 if you ever add or remove an item.
This class can be in addition to any other classes you already have on the elements. I'll call it showme:
<input type="text" class="form-control showme" aria-describedby="page">
Now you can use $('.showme') to get a jQuery object containing all the elments that have this class.
If you have to run some logic on each matching element, you would use .each(), like this:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
if( $(element).css('visibility') == 'hidden' ) {
$(element).css( 'visibility', 'visible' );
}
});
});
But you don't need to check whether an element has visibility:hidden before changing it to visibility:visible. You can just go ahead and set the new value. So you can simplify the code to:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
$(element).css( 'visibility', 'visible' );
});
});
And now that the only thing we're doing inside the loop is setting the new visibility, we don't even need .each(), since jQuery will do the loop for us when we call .css(). (Thanks #TemaniAfif for the reminder.)
So the code becomes very simple:
$('#tryBTN').click( function() {
$('.showme').css( 'visibility', 'visible' );
});

Expanding menu not responding

I'm trying to fix a mobile menu in a WordPress child theme (from Twentyseventeen) that is no longer expanding when 'menu' is clicked. Basically I've had to tear the header apart to move things around and now the aria expanded menu isn't recognised. Instead I'm trying to use javascript to change the display property of the ul from none to block, but this isn't working either - mostly because I don't know the first thing about js and I've just tried making something from bits and pieces of code.
The demo of the site is live at http://www.histeve.co.uk/testing/triangledrivertraining/
The javascript I'm trying to use is as follows:
<script>
var element = document.getElementById("topMenu");
document.getElementById("navBtn").addEventListener("click", toggleNav);
function toggleNav() {
if( element.style.display == 'none' ) {
function show() {('#topMenu').css ('display:block');}
} else {
function hide() {('#topMenu').css ('display:none'); }}
}
</script>
This is no longer kicking out errors, but it's not doing anything at all.
If anyone has any ideas, your help is greatly appreciated!
Thanks
Steve
Try this:
<script>
var $topMenu = jQuery("#topMenu");
jQuery("#navBtn").click(toggleNav);
function toggleNav() {
if($topMenu.is(":visible")) {
$topMenu.hide();
} else {
$topMenu.show();
}
}
</script>
UPDATE:
To always show the menu on desktop you should go with this solution:
Add following styles to your page:
<style>
#media (max-width: 768px) {
.menu-navigation-container {
display: none;
}
.menu-navigation-container.show-on-mobile {
display: block;
}
}
</style>
Add use this JS:
<script>
var $topMenu = jQuery(".menu-navigation-container");
jQuery("#navBtn").click(function(){
$topMenu.toggleClass("show-on-mobile");
});
</script>
You should fix your both selector which should start with $ (since it is wordpress you might have to user jquery instead of $) as well as your css function as follows.
<script>
var element = document.getElementById("topMenu");
document.getElementById("navBtn").addEventListener("click", toggleNav);
function toggleNav() {
if( element.style.display == 'none' ) {
function show() {$('#topMenu').css ('display','block');}
} else {
function hide() {$('#topMenu').css ('display','none'); }}
}
</script>
Alternative
Instead of using css you can toggle class which is much easier
function toggleNav() {
$('#topMenu').toggleClass('active');
}
then in css
#topMenu{display: none;}
#topMenu.active{display: block;}

Hiding content depending on variable value

I am making a price estimator.
How would correctly write a jQuery function that checks a variable and depending on that amount hides/shows a certain div element accordingly.
So if I had:
a HTML div with the ID 'Answer'
<div id="answer">Hide Me</div>
$("#answer")...
a variable (this variable would change)
var x = 30
Now I know the css to hide the div would be:
#answer{
visibilty:hidden;
}
What would be the correct way to hide the function checking these certain parameters? for example if x > 20 then hide etc
Now I know there will be many ways to do this and they may not require jQuery, please inform me if this is the case. Perhaps it just needs JS. I know there will be many ways to do it not just one so if you have a different way please comment as I am keen to learn.
Any help would be greatly appreciated.
Cheers
F
Note that you can also remove or add a class:
$('#answer').removeClass('hide');
$('#answer').addClass('hide');
But what you want to do is $('#answer').hide(); or $('#answer').show();
Execute this function providing the variable v:
var checkVar = function(v) {
var target = $('#answer');
if (parseInt(v) > 20) {
target.hide();
} else {
target.show();
}
}
For example, if the variable comes form a selection:
$('#selectId').on('change', function() {
checkVar($(this).val());
});
Remove the CSS. You can do it in jQuery
if(x>20){
$('#answer').hide();
}
You can use this one
$("#answer").hide();
#kapantzak's answer looks good. But keep your logic and style separated and if your not going to use the variable for the actual element twice, I wouldn't make it. So go:
var checkVar = function(var) {
var element = $('#answer');
if (parseInt(var) > 20) {
element.addClass('hidden');
}else{
element.removeClass('hidden');
}
}
And in your CSS go:
#answer.hidden{
display: none;
}
Also, depending on your preference, display: none; doesn't display anything of the object whereas visibility: hidden hides the object but the space the object was occupying will remain occupied.
HTML
<input id="changingValue">
...
<div id="answer">Hide Me</div>
CSS (not mandatory if you check values on loading)
#answer{ display:none;}
JS
var limit = 20;
$(function(){
$("#changingValue").change(function(){
if(parseInt($("#changingValue").val())<limit) { $("#answer").show(); }
else { $("#answer").hide(); }
});
});

How can I hide a button when scrolled to the top of a page?

I'm trying to adapt this JSFiddle to make the menu button on my website hide when I'm at the top of the page and show when I start scrolling down.
I modified the JS to match the CSS on my site. Then I placed it in tags in the head of my page
var $scb = $('<div class="toggle-menu-wrap"></div>');
$('.top-header').append($scb);
var $ccol = $('.content');
$ccol.scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
However, it still doesn't work. Am I making a mistake in how I'm modifying the JS to fit my CSS?
You can include the toggle-menu-wrap element in your HTML from the start. There is no need to insert it using JS.
Write the one line of CSS you need, which is to hide the element from the beginning
.toggle-menu-wrap {
display: none;
}
Your version of jQuery uses 'jQuery' instead of '$' to reference itself. I would also re-write your JS like:
jQuery(document).ready(function() {
fadeMenuWrap();
jQuery(window).scroll(fadeMenuWrap);
});
function fadeMenuWrap() {
var scrollPos = window.pageYOffset || document.documentElement.scrollTop;
if (scrollPos > 300) {
jQuery('.toggle-menu-wrap').fadeIn(300);
} else {
jQuery('.toggle-menu-wrap').fadeOut(300);
}
}
Like #murli2308 said in the comments above, you need to attach a scroll event listener to the window:
$(document).ready(function () {
var $scb = $('<div class="scroll-border"></div>');
$('.above').append($scb);
var $ccol = $('.content');
$(window).scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
})
Wrapping your code in $(document).ready() would also be a good idea.
The reason $ccol.scroll(function() { ... works in that fiddle is because of the CSS:
.content{
height: 200px;
width: 200px;
overflow: auto;
}
Notice overflow: auto;. This causes that specific div to be scrollable. However, on your website, you scroll the entire page, not $ccol. This means the event handler will never fire a scroll event (since $ccol will never scroll).
You might have forgotten to link Jquery.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Link this inside your head tag incase.....
This should do the job:
$(window).scroll(function(e){
if ($(this).scrollTop() > 0) {
$(".your_element").css("display", "block");
} else {
$(".your_element").css("display", "none");
}
});

Javascript Collapsible Menu (hide the other elements)

I have the following working Javascript function:
function collapsible(zap) {
if (document.getElementById) {
var abra = document.getElementById(zap).style;
if (abra.display == "block") {
abra.display = "none";
} else {
abra.display = "block";
}
return false;
} else {
return true;
}
}
When I use the following in html code it displays or hides the "element" div:
<li>Element</li>
Thats working fine. But the problem is, that I want to use the function for multiple links, and then the other elements, that were clicked before, stay, open.
How can I reprogram the code, so that only one div stays open and the other gets closed if i click on another link?
Thanks beforehand!
If you could use jQuery and more importantly jQueryUI accordion I think it would accomplish exactly what you're looking for.
However, without using those two, here is how I would structure it. Like mentioned above, I would use classes to modify the styles of the divs you want shown or hidden. Then the js code can just toggle those classes on each of your elements. The slightly more difficult part (without jquery) is modifying class values since in your final application you may have lots of classes on each div. This is just a very crude example to get you going.
Working JSFiddle Example
Sample DOM
<div >
<li>Element1</li>
<div id='elem1' class='myelem visible'>
Element 1 contents
</div>
</div>
<div >
<li>Element2</li>
<div id='elem2' class='myelem'>
Element 2 contents
</div>
</div>
<div >
<li>Element3</li>
<div id='elem3' class='myelem'>
Element 3 contents
</div>
</div>
Sample JS
window['collapsible'] = function(zap) {
if (document.getElementById)
{
var visDivs = document.getElementsByClassName('visible');
for(var i = 0; i < visDivs.length; i++)
{
visDivs[i].className = visDivs[i].className.replace('visible','');
}
document.getElementById(zap).className += " visible";
return false;
}
else
return true;
}
Sample CSS:
.myelem {
display: none;
}
.visible {
display: block;
}
The way to go is to create a class(or maybe two), like collapsible and active or open that has this style(display: block or none) and then you working adding or removing the class.
The logic would be:
Links that has the class collapsible when clicked would add the active or open class which would give the behavior that remains opens(or active) by css.
If you want to hide others elements you would look for the elements with the class collapsible and then remove the active(or open) class if has any.
Here is my solution: http://jsfiddle.net/g5oc0uoq/
$('.content').hide();
$('.listelement').on('click', function(){
if(!($(this).children('.content').is(':visible'))){
$('.content').slideUp();
$(this).children('.content').slideDown();
} else {
$('.content').slideUp();
}
});
show() and hide() can be used instead of slideUp() and slideDown() if you have performance issues.

Categories