Jquery Toggle states issue - javascript

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");});
});

Related

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

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!

Javascript doesn't work after website transfer

I have some issue with javascript after website transfer. All others scripts works fine but not this one
On demo version it works fine, but on live it do nothing and its giving 0 errors.
var vienasloop = true;
if (vienasloop) {
if (window.location.hash) {
$('li').on('click', function() { //here
first = $(this).siblings().eq(0).detach();
$(this).parent().prepend($(this).after(first).detach());
});
if (window.location.hash != "") {
$('li').eq(Number(window.location.hash.slice(1)) + 2).click();
}
}
}
$('body').html(String($('body').html()).replace("var vienasloop = true;",
"var vienasloop = false;"));
}
Jsfiddle
because in your code, the one property doesn't exist, try something like this :
if(window.location.hash) {
$('li').on('click' , function() { //here
first = $(this).siblings().eq(0).detach();
$(this).parent().prepend($(this).after(first).detach());
});
if (window.location.hash != "") {
$('li').eq(Number(window.location.hash.slice(1)) + 2 ).click();
}
}

Loader auto-fades in (jQuery/javascript/Bootstrap)

I'm probably an idiot, but I can't find where's problem.
There is a "Suggest a word" button at the bottom of this page.
After filling out the form and clicking on send a loader shows up, however, it doesn't disappear when ajax finishes (it fades out and fades in unexpectedly).
I have no idea why it fades in again and I can't find the reason behind this.
Here is the most important piece of code (I hope so).
$('#suggestQuestionModal').on('show.bs.modal', function (e) {
var currFormGroup = 0;
var maxFormGroups = 4;
//while(currFormGroup < maxFormGroups) {
$('#suggestionSend').click(function() {
if (validator.form()) {
$("#suggestQuestionModal .form-group").fadeOut('slow', function() {
$("#suggestLoading").fadeIn('slow');
$("#suggestionSend").attr('disabled', true);
});
if ($("#suggest-email").val() != '' && $("#suggest-want-mail").prop('checked'))
email = $("#suggest-email").val();
else
email = 'NULL';
word = $("#suggest-word").val();
pack = $("#suggest-pack").val();
lang = $("#suggest-lang").val();
var request = $.ajax({
url: "/ajax/suggestQuestion.php",
method: "POST",
data: {word: word, pack: pack, lang: lang, email: email}
});
$("#suggestQuestionModal .form-group").hide().children(':input').val('');
$('#suggestQuestionModal .form-group > :checkbox').prop('checked', false);
request.error(function(xhr,status,error) {
$("#suggestLoading").fadeOut('slow', function() {
$("#suggestQuestionModal .modal-body div.alert").addClass('alert-danger').html("<?=$lg['suggest_error']?> <a class=\"alert-link reset-suggestion\"><br><?=$lg['try_again']?></a>").fadeIn('slow');
setTimeout(function() {
$('#suggestQuestionModal').modal('hide');
}, 10000);
});
});
request.success(function(result, status, xhr) {
if (result == "OK") {
$("#suggestLoading").fadeOut('slow', function() {
$("#suggestQuestionModal .modal-body div.alert").addClass('alert-success').html("<?=$lg['suggest_success']?> <a class=\"alert-link reset-suggestion\"><br><?=$lg['suggest_add_another']?></a>").fadeIn('slow');
});
}
else {
$("#suggestLoading").fadeOut('slow', function() {
$("#suggestQuestionModal .modal-body div.alert").addClass('alert-danger').html("<?=$lg['suggest_error_info']?> "+result+" <a class=\"alert-link reset-suggestion\"><br><?=$lg['try_again']?></a>").fadeIn('slow');
});
}
});
$("#suggestQuestionModal .modal-body").on('click', '.reset-suggestion', function() {
resetSuggestionModal();
});
}
});
showGroups();
function showGroups() {
$('#suggestQuestionModal .form-group > :input').on("change", function() {
if ($(this).parent().index() == currFormGroup) {
if (currFormGroup < maxFormGroups) {
currFormGroup++;
$('#suggestQuestionModal .form-group:eq('+currFormGroup+')').fadeIn('slow');
if (currFormGroup == 4) {
$('#suggest-email').rules('add', {required: true, email: true});
}
}
}
});
}
$('#suggestQuestionModal .form-group:eq(3) > :input').change(function() {
/*if ($(this).checked && $('#suggestQuestionModal .form-group:eq(4)').css('display') == 'none') {
alert("SHOW IT!");
$('#suggestQuestionModal .form-group:eq(4)').fadeIn('slow');
currFormGroup++;
alert(currFormGroup);
} */
if (!$(this).prop('checked') && $('#suggestQuestionModal .form-group:eq(4)').css('display') == 'block') {
$('#suggestQuestionModal .form-group:eq(4)').fadeOut('slow').children(':input').val('');
currFormGroup = currFormGroup - 1;
$('#suggest-email').rules('add', {required: false, email: false});
}
});
//}
AFAIK (I tried to debug it with alerts) something bad happens right before $('#suggestionSend').click closing bracket.
BTW. Yes, I know the code is really a piece of mess.
Any help - greatly appreciated.
You can try using Ajax done instead
request.done(function( result) {
$( "#element" ).fadeout() ;
});
I've got no idea of what happened.
Tried several times - no luck.
Then I decided to try with hide() and show() - still no luck.
After I changed it back to fadeIn() and fadeOut() - it suddenly works.
Some serious magic is going on...
EDIT: I've found it. I forgot that I moved fadeIn function outside of .form-group fadeOut, so from this:
$("#suggestQuestionModal .form-group").fadeOut('slow', function() {
$("#suggestLoading").fadeIn('fast');
$("#suggestionSend").attr('disabled', true);
});
I got this:
$("#suggestQuestionModal .form-group").fadeOut('slow', function() {
$("#suggestionSend").attr('disabled', true);
});
$("#suggestLoading").fadeIn('fast');
Previously, fadeIn function was being called 4 times (because of those .form-group elements).
Now it works great :)

My signs aren't changing

I am new to JS just playing around to understand how it works.
Why isn't my sign (+,-) changing?
When the div expand it remains with a + sigh never goes to -
Thanks
$(document).ready(function(){
$(".expanderHead").click(function(){
$(this).next(".expanderContent").slideToggle();
if ($(".expanderSign").text() == "+"){
$(".expanderSign").html("−")
}
else {
$(".expanderSign").text("+")
}
});
});
Just guessing at the relationship, since you haven't shown your HTML, but you probably need something like this:
$(document).ready(function () {
$(".expanderHead:visible").click(function () {
var content = $(this).next(".expanderContent");
var sign = $(this).find(".expanderSign");
if (content.is(":visible")) {
content.slideUp();
sign.text("+");
} else {
var expanded = $(".expanderContent:visible");
if (expanded.length > 0) {
expanded.slideUp();
expanded.prev(".expanderHead").find(".expanderSign").text("+");
}
content.slideDown();
sign.text("-");
}
});
});
FIDDLE

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);
});

Categories

Resources