use if statement to check if an element is display: block jquery - javascript

I'm trying to check if an element is display block, and if it is then i want to execute some code. Below is my code, its a large function but where I'm trying to check if a div is display block is at the bottom, and if it is display block then i want to execute the blur method.
As you can see near the bottom, I started writing if ($suggestionsWrapper === and my intention was to write if suggestions wrapper is display none, then do this. I just can't figure out how to execute this, what I've written doesn't work. Also I am new to all of this so sorry if this is really messy or doesn't make sense, still very much learning.
//Header Search Handler
function headerSearchHandler(){
var $searchInput = $(".header-search input[type=text]"),
$searchSubmit = $(".header-search input[type=submit]"),
$mobSearchBtn = $(".mobile-search-btn"),
$myAccountText = $(".menu-utility-user .account-text"),
$miniCart = $("#header #mini-cart"),
$searchForm = $(".header-search form"),
$headerPromo = $(".header-promo-area");
$suggestionsWrapper = $('#suggestions-wrapper');
//
$mobSearchBtn.on("click touchend", function(e) {
$(this).hide();
//$myAccountText.hide();
$searchInput.show();
$searchInput.addClass('grey-line');
$searchSubmit.show();
$miniCart.addClass("search-open");
$searchForm.addClass("search-open");
setTimeout(function() {
$searchInput.addClass("active").focus();
}, 100);
e.stopPropogation();
});
$searchInput.on("click touchend", function(e) {
$searchInput.addClass('grey-line');
e.stopPropogation();
}).blur(function(e) {
var $this = $(this);
if($this.hasClass("active")){
$this.removeClass("active");
$searchSubmit.hide();
$mobSearchBtn.show();
$miniCart.removeClass("search-open");
$searchForm.removeClass("search-open");
}
});
$searchInput.focus(function(e){
$(this).css('width', '145px');
})
if ($suggestionsWrapper.css('display') == 'none') {
$searchInput.blur(function(e){
$(this).removeClass('grey-line');
$(this).css('width', '145px');
}
})
}//End Header Search Handler

You can create a helper method to check if display is block or not :
function checkDisplay(element) {
return $(element).css('display') == 'block';
}
Then you can check it like :
if(checkDisplay("#myElement")){
console.log("Display is Block")
}
else {
console.log("Display is NOT Block")
}
here is an example : https://jsfiddle.net/fafgqv7v/

You can do something like this I think:
if ($suggestionsWrapper.css('display') == 'block')
{
// true
} else {
// false
}
Based off of your code I think you have the }) wrong, it should be:
if ($suggestionsWrapper.css('display') == 'none') {
$searchInput.blur(function(e){
$(this).removeClass('grey-line');
$(this).css('width', '145px');
})
}
I hope this helps!

Related

How to optimize this javascript duplicates

I wrote this code, but since I'm just starting to learn JS, can't figure out the best way to optimize this code. So made a duplicates for every if statement.
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$('.lang').hide();
$('.lang-all').click(function(){
$('.lang-all').hide();
$('.lang').slideToggle(200);
});
} else {
$('.lang').show();
$('.lang-all').hide();
}
if(gender.length == gender.filter(":checked").length){
$('.gender').hide();
$('.gender-all').click(function(){
$('.gender-all').hide();
$('.gender').slideToggle(200);
});
} else {
$('.gender').show();
$('.gender-all').hide();
}
});
So this is my code, as you can see on line 15 if(gender... I have a duplicate of previous code, just changed variable from "lang" to "gender". Since I have more that two variables, I don't want to make duplicate of code for every each of them, so I hope there is a solution to optimize it.
You can write a function to let your code more abstract, see:
function isChecked(obj, jq1, jq2){
if(obj.length == obj.filter(":checked").length){
jq1.hide();
jq2.click(function(){
jq2.hide();
jq1.slideToggle(200);
});
} else {
jq1.show();
jq2.hide();
}
}
//Your jQuery code, more abstract
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
isChecked(lang, $('.lang'), $('.lang-all'));
isChecked(gender, $('.gender'), $('.gender-all'));
});
make a function which had similar functionality, then pass a parameter as a class or id
$(function() {
call('.lang');
call('.gender');
function call(langp){
var lang = $(langp+" input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$(langp).hide();
$(langp+'-all').click(function(){
$(langp+'-all').hide();
$(langp).slideToggle(200);
});
} else {
$(langp).show();
$(langp+'-all').hide();
}
}
});

Transfer javascript to jQuery for the carousel

I am trying to convert the JavaScript to jQuery for my carousel.
The code I had is:
document.querySelectorAll('.indicators')[0].style.color = 'red';
document.querySelector('.toggler-prev').style.display = 'none';
document.addEventListener('postchange', function(event){
document.querySelectorAll('.indicators')[event.lastActiveIndex].style.color = 'white';
document.querySelectorAll('.indicators')[event.activeIndex].style.color = 'red';
var togglerPrev = document.querySelector('.toggler-prev');
var togglerNext = document.querySelector('.toggler-next');
if (event.activeIndex === 3) {
togglerPrev.style.display = 'block';
togglerNext.style.display = 'none';
} else if (event.activeIndex === 0) {
togglerNext.style.display = 'block';
togglerPrev.style.display = 'none';
} else {
togglerNext.style.display = 'block';
togglerPrev.style.display = 'block';
}
});
Which I transferred to jQuery:
$('.indicators').css('color','#000');
$('.toggler-prev').css('display','none');
$(window).on('postchange', function(event){
$('.indicators')[event.lastActiveIndex].css('color','#FFF');
$('.indicators')[event.activeIndex].css('color','#000');
var togglerPrev = $('.toggler-prev');
var togglerNext = $('.toggler-next');
if (event.activeIndex === 3) {
togglerPrev.css('display','block');
togglerNext.css('display','none');
} else if (event.activeIndex === 0) {
togglerNext.css('display','block');
togglerPrev.css('display','none');
} else {
togglerNext.css('display','block');
togglerPrev.css('display','block');
}
});
But it isn't working as I expected for example togglers are not being hidden and color of indicators not being changed.
This is the working JS example: http://codepen.io/anon/pen/eJYWQO
And my jQuery alternative: http://codepen.io/anon/pen/eJYWrq
Can anybody help me with editing my second codepen? Thanks in advance.
You forgot to mention somewhere that you are using AngularJS and onsenUI ;)
Your problem is, that the jQuery event does not have the properties activeIndex and lastActiveIndex, but they can be found in event.originalEvent.
Also, like #stalin said in his answer, your indicators are no jQuery objects, therefore you can't call the css-function on them. Wrap this stuff in another jQuery constructor like $() or even better, use the eq-function which returns a jQuery wrapped object from an array.
Then, to optimize some of the readability, you might want to consider the hide and show function instead of changing the CSS property display.
All in all your code should look like this
$('.indicators').css('color', '#fff');
$('.indicators').eq(0).css('color', '#000'); // highlight the first indicator
$('.toggler-prev').hide();
$(window).on('postchange', function(event) {
//store the indices for readability
var activeIndex = event.originalEvent.activeIndex;
var lastActiveIndex = event.originalEvent.lastActiveIndex;
$('.indicators').eq(lastActiveIndex).css('color', '#FFF');
$('.indicators').eq(activeIndex).css('color', '#000');
var togglerPrev = $('.toggler-prev');
var togglerNext = $('.toggler-next');
if (activeIndex === carousel.getCarouselItemCount() - 1) {
togglerPrev.show();
togglerNext.hide();
} else if (activeIndex === 0) {
togglerNext.show();
togglerPrev.hide();
} else {
togglerNext.show();
togglerPrev.show();
}
});
You have several problems in your implementation
First the event is not trigered in $(window) is in the $(document)
Your variable like lastActiveIndex are not in the event object are in event.originalEvent
$('.indicators')[event.lastActiveIndex] return a dom object not a jquery object you need to wrap this result in a jquery object to use the css() function
After you fix all this your code will work
Sorry that don't have time for create a fiddle for you :)

Wait until div is not visible to process next line

I need to write some code which is supposed to wait until a predefined div is no longer visible in order to process the next line. I plan on using jQuery( ":visible" ) for this, and was thinking I could have some type of while loop. Does anyone have a good suggestion on how to accomplish this task?
$( document ).ready(function() {
$(".scroller-right" ).mouseup(function( event ) {
alert('right');
pollVisibility();
});
});
function pollVisibility() {
if ($(".mstrWaitBox").attr("visibility")!== 'undefined') || $(".mstrWaitBox").attr("visibility") !== false) {
alert('inside else');
microstrategy.getViewerBone().commands.exec('refresh');
} else {
setTimeout(pollVisibility, 100);
}
}
$( document ).ready(function() {
$(".scroller-right" ).mouseup(function( event ) {
alert('right');
pollVisibility();
});
});
function pollVisibility() {
if (!$(".mstrWaitBox").is(":visible")) {
alert('inside if');
microstrategy.getViewerBone().commands.exec('refresh');
} else {
setTimeout(pollVisibility, 100);
}
}
div when not visible:
<div class=​"mstrWaitBox" id=​"divWaitBox" scriptclass=​"mstrDialogImpl" dg=​"1" ty=​"edt">​
</div>​
div when visible:
<div class=​"mstrWaitBox" id=​"divWaitBox" scriptclass=​"mstrDialogImpl" dg=​"1" ty=​"edt" visibility="visible">​
</div>​
You can use the setTimeout function to poll the display status of the div. This implementation checks to see if the div is invisible every 1/2 second, once the div is no longer visible, execute some code. In my example we show another div, but you could easily call a function or do whatever.
http://jsfiddle.net/vHmq6/1/
Script
$(function() {
setTimeout(function() {
$("#hideThis").hide();
}, 3000);
pollVisibility();
function pollVisibility() {
if (!$("#hideThis").is(":visible")) {
// call a function here, or do whatever now that the div is not visible
$("#thenShowThis").show();
} else {
setTimeout(pollVisibility, 500);
}
}
}
Html
<div id='hideThis' style="display:block">
The other thing happens when this is no longer visible in about 3s</div>
<div id='thenShowThis' style="display:none">Hi There</div>
If your code is running in a modern browser you could always use the MutationObserver object and fallback on polling with setInterval or setTimeout when it's not supported.
There seems to be a polyfill as well, however I have never tried it and it's the first time I have a look at the project.
FIDDLE
var div = document.getElementById('test'),
divDisplay = div.style.display,
observer = new MutationObserver(function () {
var currentDisplay = div.style.display;
if (divDisplay !== currentDisplay) {
console.log('new display is ' + (divDisplay = currentDisplay));
}
});
//observe changes
observer.observe(div, { attributes: true });
div.style.display = 'none';
setTimeout(function () {
div.style.display = 'block';
}, 500);
However an even better alternative in my opinion would be to add an interceptor to third-party function that's hiding the div, if possible.
E.g
var hideImportantElement = function () {
//hide logic
};
//intercept
hideImportantElement = (function (fn) {
return function () {
fn.apply(this, arguments);
console.log('element was hidden');
};
})(hideImportantElement);
I used this approach to wait for an element to disappear so I can execute the other functions after that.
Let's say doTheRestOfTheStuff(parameters) function should only be called after the element with ID the_Element_ID disappears, we can use,
var existCondition = setInterval(function() {
if ($('#the_Element_ID').length <= 0) {
console.log("Exists!");
clearInterval(existCondition);
doTheRestOfTheStuff(parameters);
}
}, 100); // check every 100ms

make 'each' cycles occur consecutively

I have two actions I need to apply to a set of DIV's, but I need one cycle to happen before the other is finished.
Here is my code:
$("div").each(function(){
//do stuff first
}).each(function(){
//do stuff next
});
but at present, do stuff next happens before do stuff first finishes. Anything I can do to stop this?
Full Script
$("div").each(function(){
if($(this).html() === "yes"){
$(this).fadeOut(time,function(){
$(this).parent().height(0);
});
}
}).each(function(){
if($(this).html() !== "yes"){
$(this).parent().height(25);
$(this).fadeIn(time);
}
});
Knowing that you want to fadeIn and then set height, will this do what you require?
var divs = $('div');
divs.fadeIn(function () {
divs.height('200');
});
Using each to allow different settings for different divs:
$('div').each(function () {
var div = $(this), toggle = true;
div.fadeIn(function () {
if (toggle = !toggle) {
div.height('200');
} else {
div.width('200');
}
});
});
Seeing your code snippet I believe I got it now:
var yesDivs = $('div').filter(function () {
return $(this).html() === 'yes';
});
yesDivs.fadeOut(time, function () {
yesDivs.parent().height(0);
$('div').filter(function () {
return $(this).html() !== 'yes';
}).fadeIn(time).parent().height(25);
});

Jquery Toggle states issue

I'm having a problem with the following code -
function slideContactDetails() {
if (sliderState == "closed") {
$(".sliderBlock").animate({width:400}, 'slow',function() {$("div.sliderForm").fadeIn("fast"); });
sliderState = "open";
setTimeout(function(){switchImg("first")},300);
}
else if (sliderState =="open") {
$(".sliderBlock").animate({width:0}, 'slow',function() {$("div.sliderForm").fadeIn("fast"); });
sliderState="closed";
setTimeout(function(){switchImg("second")},300);
}
};
var firstState = "images/closeTab.png";
var secondState = "images/contact_us.png"
function switchImg(imgNo){
if (imgNo == "first"){
$('.contactBtnBtn img').attr("src", firstState);
$('.sliderBlockForm').show();
}
else if (imgNo == "second"){
$('.contactBtnBtn img').attr("src", secondState);
$('.sliderBlockForm').hide();
}
}
basically I'm trying to open and close an animated 'contact us' div. When opened I want the image to switch to a close image and visa-versa on close.
The issue I have is that the image switches as requested, but only for a split second as the sliderstate variable has now altered the 'else if' also appears to action and changes the image back again! I have tried to fix using timeouts, this works in all broswers apart from Chrome!
Any advise greatly received!!
Cheers
Paul
$("div.sliderForm").click(
$(this).toggle('slow');
);
Couldn't you just place the image switching in the if/else block, and remove the need for the setTimeout()?
function slideContactDetails() {
if (sliderState == "closed") {
$(".sliderBlock").animate({
width: 400
}, 'slow', function () {
$("div.sliderForm").fadeIn("fast");
});
sliderState = "open";
$('.contactBtnBtn img').attr("src", firstState);
$('.sliderBlockForm').show();
} else {
$(".sliderBlock").animate({
width: 0
}, 'slow', function () {
$("div.sliderForm").fadeIn("fast");
});
sliderState = "closed";
$('.contactBtnBtn img').attr("src", secondState);
$('.sliderBlockForm').hide();
}
};
the following worked for me based on Coding Freaks's answer.
$(".sliderBlock").hide();
$('img.slider').toggle(
function()
{
$(".sliderBlock").animate({width:400}, 'slow',function() {$('.contactBtnBtn img').attr("src", "images/closeTab.png");$('.sliderBlockForm').show();});
},
function()
{
$('.sliderBlockForm').hide();
$(".sliderBlock").animate({width:0}, 'slow',function() {$('.contactBtnBtn img').attr("src", "images/contact_us.png");});
});

Categories

Resources