How to add multiple CSS property in JavaScript If statement? [duplicate] - javascript

This question already has answers here:
JavaScript: Simple way to check if variable is equal to one of two or more values? [duplicate]
(8 answers)
Closed 3 years ago.
I have this script
$(document).ready(function() {
setInterval(function() {
if ($('#myfooter').css('visibility') == 'hidden'){
document.location.href = "http://www.templatezy.com";
}
}, 3000)
})
Since the above script have only css property "visibility:hidden" while i also want to include "visibility:collapse" property in the script by using OR operator.
So can anyone provide me coding something like below example.
$(document).ready(function() {
setInterval(function() {
if ($('#myfooter').css('visibility') == 'hidden')||.css('visibility') == 'collapse'){
document.location.href = "http://www.templatezy.com";
}
}, 3000)
})
This one is just example it does not work. I just share idea what i want..I want to use OR operator rather than using separate script for "visibility:collapse". i hope you guys will add OR operator in the existing script by adding "visibitity:collapse" proeprty too. thanks
**
OR
**
Guys You can see here.. i shared both script below...now make it one script by adjusting visibility:hidden and visibility:collapse property in one line. I hope you can now understand...using two script will increase coding make it one by using these two css property in one line. thanks
$(document).ready(function() {
setInterval(function() {
if ($('#myfooter').css('visibility') == 'hidden') {
document.location.href = "http://www.templatezy.com";
}
}, 3000)
})
$(document).ready(function() {
setInterval(function() {
if ($('#myfooter').css('visibility') == 'collapse') {
document.location.href = "http://www.templatezy.com";
}
}, 3000)
})

Simplest thing to do is get the visibility value and save it:
let vis = $("#myfooter").css("visibility");
if (vis == 'hidden' || vis == 'collapse'){
document.location.href = "http://www.templatezy.com";
}
Your solution was (as you probably noted) a syntax error. It could have been fixed by repeating $("#myfooter") on the other side of the || operator, but then you'd have two jQuery calls to go and find the same element.

You can save the visibility of the element in a variable in order to make the if statement simpler and easier to read. Also, you don't want to call $('#myfooter').css('visibility'); twice if you can do it once.
Below is an example of the same code handling both visibilities:
visibility: hidden
$(document).ready(function() {
setInterval(function() {
let visibility = $('#myfooter').css('visibility');
if (visibility == 'hidden' || visibility == 'collapse') {
document.location.href = "http://www.templatezy.com";
}
}, 3000);
});
#myfooter {
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myfooter"></div>
visibility: collapse
$(document).ready(function() {
setInterval(function() {
let visibility = $('#myfooter').css('visibility');
if (visibility == 'hidden' || visibility == 'collapse') {
document.location.href = "http://www.templatezy.com";
}
}, 3000);
});
#myfooter {
visibility: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myfooter"></div>

Related

1 line of code (console.log), two emplacement in the code = two results differents

The problem I encountered is with the jQuery Selector that returns me two different answers for the same line of code :
console.log($('.page_container')[3]);
In my navigation fonction using arrows of the keybord, this line would return me the content of this div including the parent '.page_container'.
This is exactly what I don't want since I need it as an object.
function checkKey(e) {
var actualScroll = $('.main').scrollTop();
var scrollTo = $('.page_container').height();
console.log($('.page_container')[3]);
if (e.keyCode == '38' && working == false) {
working = true;
// up arrow
$(".main").animate({
scrollTop: actualScroll - scrollTo,
}, 1000, 'easeInOutExpo', function () {
working = false;
});
} else if (e.keyCode == '40' && working == false) {
working = true;
// down arrow
$(".main").animate({
scrollTop: actualScroll + scrollTo,
}, 1000, 'easeInOutExpo', function () {
working = false;
});
}
}
$(document).ready(function () {
//ArrowsNavigations
document.onkeydown = testArrows;
});
But anywhere else in the code, it would return me the normal thing, the object version with all its original properties.
Edit :
Here is the fiddle but I don't get why I don't have the same results, anyways on this fiddle whenever I select my entire array of '.page_container' I get the object sample but if I select a particular index of this array I'll get the html of this occurence.
On my local version, the selector returns me the html content only when it's called in the checkKey function.
I think you do get an object. It's just the browser's way of displaying things.
Try this:
console.log($('.page_container')[3].id);

Unhide div using javascript object oriented

So i am having trouble unhiding a div, once it has been hidden.
The code:
First object
$('#filter_region').on('change', function(e) {
var temp_region_id = $('#filter_region').val();
filterRegionId($temp_region_id);
});
Seconds object:
function filterRegionId(temp_region_id)
{
if ($(temp_region_id) != 1) {
$('.showheadline').hide(); }
else { $('.showheadline').show(); }
}
Really what i want to do, is once the region is changed from the original, the div should be hidden - this works!
However, once the person goes back on the same region, the div is still hidden.
The filter_region echos from 1-8 depending on the region. I realise that i have set the region to 1, this is to test. However, even if the if-statement is set to 1, it still shows the divs when loaded, even if the region is 2-8. Hope this make any sense at all! Please feel free to ask if there are any questions regarding my explanation.
Best Regards,
Patrick
Try this, without the $(..) around the var
$('#filter_region').on('change', function(e) {
var temp_region_id = $('#filter_region').val();
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id)
{
if (temp_region_id != 1) {
$('.showheadline').hide();
}
else {
$('.showheadline').show();
}
}
A text input's value attribute will always return a string. You need to parseInt the value to get an integer
var temp_region_id = parseInt($('#filter_region').val(),10);
and remove the $ from variable name filterRegionId($temp_region_id); and if ($(temp_region_id) != 1) {
$('#filter_region').on('change', function(e) {
var temp_region_id = parseInt($('#filter_region').val(),10);
///parse it to integer
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id){
if (temp_region_id!= 1)
$('.showheadline').hide();
else
$('.showheadline').show();
}
The best solution is to rewrite you code a little.
Please add the filterRegion function on top and change the parametter name as follows
var temp_region_id = $('#filter_region').val();
filterRegionId(temp_region_id);
$('#filter_region').on('change', function(e) {
temp_region_id= $('#filter_region').val();
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id)
{
if ($(temp_region_id) != 1) {
$('.showheadline').hide();
}
else {
$('.showheadline').show();
}
}

Am I using the correct jQuery syntax?

I have the following code -
$(window).resize(function () {
if ($(window).width() >= 1023) {
for (var i = 0; i < seatInfo.length; i++) {
if (seatInfo[i].data == 'true') {
document.getElementById('Btn1').style.visibility = "visible";
break;
} else {
document.getElementById('Btn1').style.visibility = "hidden";
}
}
if (nameInfo[0].data == "true") {
document.getElementById('Btn2').style.visibility = "visible";
}
}
if ($(window).width() <= 1022) {
document.getElementById('Btn2').style.visibility = "hidden";
}
});
Is this is the correct way to write it? I notice that it contains a JavaScript and jQuery mix.
If you are specifically asking about the jQuery syntax then the answer is no. You are using the native JavaScript methods instead of the much shorter jQuery methods.
Take a look at some jQuery selectors. For instance:
An element with an id attribute of foo can be found using jQuery's id attribute selector #:
var element = $( "#foo" ); // match the element
Changing an elements visibility attribute is the same as changing any other css attribute:
element.css( "visibility", "visible" ); // change css properties
A great feature of jQuery is it's many shortcut methods. There are a few shortcut method to display and hide elements (and toggle them):
element.show()
element.hide()
element.toggle()
Why stop using jQuery half-way?
For document.getElementById('Btn1') use $('#Btn1').
For .style.visibility = "visible" use .show() (or, if you want to be very precise, .css('visibility', 'visible'))
There is lots of good documentation on the official jQuery site.
You can use $('#some-id').hide() and $('#some-id').show(). Instead of document.getElementById('some-id') with style.visibility = "visible" or style.visibility = "hidden".
you can use .css from jquery and set it as json structure to define one or multiple CSS attributes, this is more easier for me to remember.
$('#Btn1').css({
'property': 'value',
'property': 'value'
});
or just use it like this for a single attribute
var btn1 = $('#Btn1'),
btn2 = $('#Btn2'),
window = $(window);
window.resize(function () {
if (window.width() >= 1023) {
for (var i = 0; i < seatInfo.length; i++) {
if (seatInfo[i].data == 'true') {
btn1.css('visibility','visible');
break;
} else {
btn1.css('visibility','hidden');
}
}
if (nameInfo[0].data == "true") {
btn2.css('visibility','visible');
}
}
if (window.width() <= 1022) {
btn2.css('visibility','hidden');
}
});

jQuery.css('display') only returns inline

I am trying to get checked options from a table which are set inline. There is a search function, which sets $(element).css('display','none') on objects in which there is no match with the search. Anyways, this piece of code will only return inline, no matter what the elements are set to. Even if I manually set all of them to display: none in the table itself, the alert will return inline for every single object in the table. Is there any solution to this?
JS code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).css('display') === 'inline') {
array.push($(this).val());
}
});
}
Fundamentally, css("display") does work, so something else is going on.
I suspect one of two things:
The checkboxes that you're making display: none are never checked, and so you don't see them in your each loop.
You're not making the checkboxes display: none, but instead doing that to some ancestor element of them. In that case, $(this).is(":visible") is what you're looking for.
Here's an example of #2: Live Copy | Live Source
<div id="ancestor">
<input type="checkbox" checked>
</div>
<script>
$("#ancestor").css("display", "none");
console.log("display property is now: " +
$("input:checkbox:checked").css("display"));
console.log("visible tells us what's going on: " +
$("input:checkbox:checked").is(":visible"));
</script>
...which outputs:
display property is now: inline-block
visible tells us what's going on: false
Applying that to your code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).is(':visible')) {
// Change is here -----------------^^^^^^^^^^^^^^
array.push($(this).val());
}
});
}
Side note: Every time you call $(), jQuery has to do some work. When you find yourself calling it repeatedly in the same scope, probably best to do that work once:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
var $this = $(this); // <=== Once
i++;
alert($this.css('display'));
if ($this.val() !== 0 && $this.is(':visible')) {
// Other change is here -------^^^^^^^^^^^^^^
array.push($this.val());
}
});
}
try following:
$("input:checkbox:checked").each(function(i,o){
console.log($(this).css("display"));
});
working fiddle here: http://jsfiddle.net/BcfvR/2/

jQuery: FadeIn a selected value on click

I have a selected box with 5 values. I'm trying to fadeIn inputs of what is selected in the box. For example: If input1 is selected, fade in input1 on click.
Here is what I'm trying to do:
$(document).ready(function(){
$('.btn').click(function() {
if($("#selectbox").value == 'Input1') {
$(".input1").show();
} else if($("#selectbox").value == 'Input2') {
$(".input2").show();
} else if($("#selectbox").value == 'Input3') {
$(".input3").show();
} else if($("#selectbox").value == 'Input4') {
$(".input4").show();
} else if($("#selectbox").value == 'Input5') {
$(".input5").show();
}
}
});
And here is a NOT working fiddle:
http://jsfiddle.net/rzMHJ/
Your code have two errors and that's why its not working.
$("#selectbox").value should be $("#selectbox").val()
you have not closed your click event with );
Also its much better to use switch case in this example.
Working Demo: http://jsfiddle.net/naveen/Zn2yy/
Update (based on Nick Cravers comment)
For this particular scenario you could simplify code a lot like this.
Demo: http://jsfiddle.net/nick_craver/BWacA/
There are two problems with your code that is causing it to fail.
First, replace .value with the jQuery function val().
Second, add ); to the second to last } at the end.
Here is working refactored code:
$(document).ready(function() {
$('.btn').click(function() {
var show = "." + $("#selectbox").val().toLowerCase();
$(show).fadeIn();
});
});

Categories