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(); }
});
});
Related
Thank you, everyone!
I am keep going design my game with Javascript.
There is box, id called 'box1'.
Also, there is a hidden button.
I have a function to change the box1 class.
I want to change the visibility if the box1 has the class "glow".
In fact, I am planning to check 9 boxes class. Therefore, I may use && for "if" condition.
$(document).ready(function() {
if (document.$('#box1').classList.contains('.glow')) {
$(".btn-warning").css('visibility', 'visible');
}});
something like you can design your code
You have a 9 blocks with its like box1, box2, so on
Loops through get all class nodes
$("div[id^='box']").foreach(function(){
if($(this).hasClass(".glow"))
{
// your logic
$(".btn-warning").css('visibility', 'visible');
}
}
I hope this will work for you
Thank you everyone for your comments.
I change my logic.
I finish the code myself.
gameboxsize is the div for 9boxes.
setInterval(function() {
var gamebox = document.getElementById('gameboxsize');
var nodesSameClass = gamebox.getElementsByClassName('glow');
console.log(nodesSameClass.length);
var winNum = nodesSameClass.length;
if (winNum === 9) {
$(".btn-warning").css('visibility', 'visible');
}
});
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' );
});
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>
I set out on a journey to create an iTunes-like search using Javascript. I learned about jQuery, and with some help from people on StackOverflow, I was successful.
I've come back here to share with you a very simple way to create a dynamic hide/show list based on the user input.
Let's search!
The entirety of the tutorial code can be found here.
And a JSFiddle for it is here!
So good to see Nick was successful on this experiment. good job on learning how to do it :)
Just in case you haven't encountered this jquery plugin, you might want to take a look at it too it's called Quick search.
https://github.com/riklomas/quicksearch
And I've used it on numerous pages and it works like a charm. example:
http://fedmich.com/works/types-of-project.htm
First, create a simple Div Layout with some text in the divs and search bar above it.
<div class="search_bar">
<form><!--The Field from which to gather data-->
<input id="searchfield" type="text" onclick="value=''" value="Case Sensitive Search">
</form>
</div>
<!--Containers With Text-->
<div class="container">
<div class="container_of_hc">
<div class="horizontal_containers">Cat</div>
<div class="color">Black</div>
<div class="color">White</div>
<div class="color">Orange</div>
</div>
<div class="horizontal_containers">Dog</div>
<div class="horizontal_containers">Rat</div>
<div class="horizontal_containers">Zebra</div>
<div class="horizontal_containers">Wolf</div>
</div>
CSS:
.container {
width: 100%;
}
.horizontal_containers {
height:10%;
border: solid 3px #B30015;
font-size: 45px;
text-align: center;
}
Second, you will make a script utilizing jQuery. Remember the title says this is a Dynamic Search, meaning (for us) we want to update the search with each key typed:
$("#searchfield").keyup(function() {
Note: Need a selector refresher?
Then we will set a variable to the value in #searchfield:
var str = $("#searchfield").val(); //get current value of id=searchfield
To ensure we show all the divs in our list when there is nothing in the searchfield we create an if statement based on the length of our new variable (str):
if (str.length == 0) {
//if searchfield is empty, show all
$(".horizontal_containers").show();
}
Last, we do the actual hiding of the divs if the length of str is not 0:
else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$("div:contains('" + str + "').horizontal_containers").show();
$("div:not(:contains('" + str + "')).horizontal_containers").hide();
}
});
The div:contains() and div:not(:contains()) statements are what set the conditions. It's essentially an if statement. They search the text contained within the div, not the div attributes. If you want to search a deeper div structure you can use more than one selector in the script's jQuery statements like so:
if (str.length == 0) {
//if searchfield is empty, show all
$(".container .color").show();
} else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$(".container div:contains('" + str + "').color").show();
$(".container div:not(:contains('" + str + "')).color").hide();
}
Replace the script statement you already have to give it a try.
Note: The nesting structure of your divs must match that in your selector.
And that's essentially it. If you have tips to improve this, know how to change it to a case insensitive search, or anything else you can think of, please let me know!
Thanks to MrXenoType I have learned case insensitivity for the :contains function.
To create a case insensitive search for this project simply add:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
This creates a pseudo for the contains function. Place this code above your other script (within the same script) to make true for only this script.
Try:
$.expr[":"].contains_nocase = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
for adding a :contains_nocase() selector with jQuery 1.8
i have a same question asked here(wasnt able to comment on it,maybe dont have a priviledge) , i want to get css width value defined in stylesheet but not yet applied on any element in dom ,(its bootstrap css with grid with responsive media queries)
.span6 {
width: 570px;
}
However solution provided in above referenced question return 0 i.e like this
$('<div/>').addClass('span6').width();
but works if i do something like this
$('<div/>').addClass('span6').hide().appendTo('body').width();
any easy way without appending that div?
In order to read a CSS property value from a nonexistent element, you need to dynamically insert that element (as hidden) to the DOM, read the property and finally remove it:
var getCSS = function (prop, fromClass) {
var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
$("body").append($inspector); // add to DOM, in order to read the CSS property
try {
return $inspector.css(prop);
} finally {
$inspector.remove(); // and remove from DOM
}
};
jsFiddle here
Great answer by Jose. I modified it to help with more complex css selectors.
var getCSS2 = function (prop, fromClass, $sibling) {
var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
if($sibling != null){
$sibling.after($inspector); //append after sibling in order to have exact
} else {
$("body").append($inspector); // add to DOM, in order to read the CSS property
}
try {
return $inspector.css(prop);
} finally {
$inspector.remove(); // and remove from DOM
}
};
JSFiddle