I am trying to write an if else statement to trigger one class when another one is clicked under the condition that the one class has a marginTop of -200px.
I tried using this if statement but it doesn't work:
if ($('.logintrigger').click() && $('.register').css('marginTop') === '-200px') {
$('.registertrigger').toggle(
function () {$('.register').stop().animate({'marginTop':'-0px'},200); $('#opencloseregister').css({'backgroundPosition':'-20px 0px'});}
);
}
Any suggestions???
Made a jsfiddle with an example of proper ifelse with jquery. http://jsfiddle.net/RQ75m/
$(".logintrigger").click(function(){
if( $(".register").css("margin-top") == "200px" ){
$(".registertrigger").show(); //toggle function here
return false; //so that the page doesn't refresh
} else {
$(".registertrigger").hide();
return false; //so that the page doesn't refresh
}
});
It sounds like you simply need to rework your expression. The problem is you're trying to see if an element is 'clicked', when you should just attach an event handler.
$('.loginTrigger').click(function()
{
if('.register').css('marginTop') === '-200px')
{
// Do Stuff
}
});
you are calling the click event, i think you want to add an event to the click event...
$('.logintrigger').click( function(e){
if($('.register').css('marginTop') === '-200px'){
$('.registertrigger').toggle();
}
});
When you are calling $('.logintrigger').click(), it is triggering click event.
it should be:
if ($('.logintrigger').click(function(){
if ($('.register').css('marginTop') === '-200px') {
$('.registertrigger').toggle(
function () {
$('.register').stop().animate({'marginTop':'-0px'},200);
$('#opencloseregister').css({'backgroundPosition':'-20px 0px'});
}
);
}
})
$('.logintrigger').on('click', function(){
if($('.register').css('marginTop')==='200px') {
$('.registertrigger').toggle( function () {
$('.register').stop().animate({'marginTop': 0 },200);
$('#opencloseregister').css({'backgroundPosition':'-20px 0px'});
});
}
});
Related
I currently have sections of a form which display based on the selection of a drop down list:
$('#Selection').on('change', function () {
if(this.value === "Section1"){
$("#Section1").show();
} else {
$("#Section1").hide();
}
if(this.value === "Section2"){
$("#Section2").show();
} else {
$("#Section2").hide();
}
if(this.value === "Section3"){
$("#Section3").show();
} else {
$("#Section3").hide();
}
if(this.value === "Section4"){
$("#Section4").show();
} else {
$("#Section4").hide();
}
if(this.value === "Section5"){
$("#Section5").show();
} else {
$("#Section5").hide();
}
});
This works well for my 'Add' function because the default drop down list selection is 'Please Select...' which means there is a 'change' which triggers my function.
For my 'Edit' function, a selection has already been made, and it's unlikely a change to this selection will be made. I've tried to change the .on('change') bit to .on('load') but that doesn't seem to work!
It feels like there is a simple change I need to make, but I'm rubbish at javaScript!
Thanks.
Try this one:
$( document ).ready(function() {
// Handler for .ready() called.
$("#Section1").show();
});
Try to trigger your code manually on document ready like so:
$(document).ready(function(){
$("#Selection").trigger("change");
});
If you are happy with the functionality inside your change handler;
I think Klikas solution is the correct one:
$(document).ready(function(){
if($('#Selection').value!=""){$('#Selection').trigger("change");}
});
You can simplify your long function with something like this:
$('#Selection').on('change', function(){
var p=["Section1", "Section2", "Section3", "Section4", "Section5"];
for(var i=0; i<p.length; i++){var n=p[i]; var t=$("#"+n); if(t){this.value===n?t.show():t.hide();}}
});
I made a simple plunkr here http://plnkr.co/edit/zNb65ErYH5HXgAQPOSM0?p=preview
I created a little datepicker I would like this to close itself when you focus out of it (focusout of datepicker) if I put blur on input I'm unable to use the datepicker, if I put focusout event on datepicker it doesn't works
I also tried:
angular.element(theCalendar).bind('blur', function () {
$scope.hideCalendar();
});
but it doesn't work.
Any clue?
this is because you are removing the item before you get a chance to do anything, here is a working example:
http://plnkr.co/edit/mDfV9NLAQCP4l7wHdlfi?p=preview
just add a timeout:
thisInput.bind('blur', function () {
$timeout(function(){
$scope.hideCalendar();
}, 200);
});
have you considered using existing datepickers? like angularUI or angular-strap: http://mgcrea.github.io/angular-strap/##datepickers
Update:
Not a complete solution, but should get you quite closer:
angular.element($document[0].body).bind('click', function(e){
console.log(angular.element(e.target), e.target.nodeName)
var classNamed = angular.element(e.target).attr('class');
var inThing = (classNamed.indexOf('datepicker-calendar') > -1);
if (inThing || e.target.nodeName === "INPUT") {
console.log('in');
} else {
console.log('out');
$timeout(function(){
$scope.hideCalendar();
}, 200);
}
});
http://plnkr.co/edit/EbQl5xsCnG837rAEhBZh?p=preview
What you want to do then is to listen for a click on the page, and if the click is outside of the calendar, then close it, otherwise do nothing. The above only takes into account that you are clicking on something that has a class name which includes datepicker-calendar, you will need to adjust it so that clicking within the calendar doesn't close it as well.
How about closing on mouseout?
You need to cancel the close if you move to another div in the calendar though:
//get the calendar as element
theCalendar = element[0].children[1];
// hide the calendar on mouseout
var closeCalendarTimeout = null;
angular.element(theCalendar).bind('mouseout', function () {
if ( closeCalendarTimeout !== null )
$timeout.cancel(closeCalendarTimeout);
closeCalendarTimeout = $timeout(function () {
$scope.hideCalendar();
},250)
});
angular.element(theCalendar).bind('mouseover', function () {
if ( closeCalendarTimeout === null ) return
$timeout.cancel(closeCalendarTimeout);
closeCalendarTimeout = null;
});
EDIT
Adding a tabindex attribute to a div causes it to fire focus and blur events.
, htmlTemplate = '<div class="datepicker-calendar" tabindex="0">' +
angular.element(theCalendar).bind('blur', function () {
$scope.hideCalendar();
});
So, i know it probably is not the best practice or the best way to do this, but at the end i fixed and got what i need using this:
thisInput.bind('focus click', function bindingFunction() {
isMouseOnInput = true;
$scope.showCalendar();
angular.element(theCalendar).triggerHandler('focus');
});
thisInput.bind('blur focusout', function bindingFunction() {
isMouseOnInput = false;
});
angular.element(theCalendar).bind('mouseenter', function () {
isMouseOn = true;
});
angular.element(theCalendar).bind('mouseleave', function () {
isMouseOn = false;
});
angular.element($window).bind('click', function () {
if (!isMouseOn && !isMouseOnInput) {
$scope.hideCalendar();
}
});
I setted up some boolean vars to check where mouse is when you click the page and it works like a charm if you have some better solution that works , please let me know, but this actually fixed all.
I accept this as the answer but i thank all the guys on this page!
So I have something like:
$('#friendRequests').on('click', '.acceptFriendRequest', function (event) {
// code here
}
How could I make the click of .denyFriendRequest to run that same function above, and to know which button was clicked (to decide whether to accept or deny the request in my backend)
Thank you
Use Multiple Selector (“selector1, selector2, selectorN”) to bind event to multiple elements and use this, $(this) or this.target to refer to current element.
Live Demo
$('#friendRequests').on('click', '.acceptFriendRequest, .denyFriendRequest', function (event) {
alert(this.className);
//alert($(this).attr('class');
//alert(event.target.className);
});
If you expect the element to have multiple classes and you need if one of classes would be .acceptFriendRequest or .denyFriendRequest then you can use .hasClass()
$('#friendRequests').on('click', '.acceptFriendRequest, .denyFriendRequest', function (event) {
if($this).hasClass('acceptFriendRequest')
{
}
if($this).hasClass('denyFriendRequest')
{
}
});
try using jquery hasClass():
$('#friendRequests').on('click', function (event) {
if ($(this).hasClass("acceptFriendRequest")) {
//
} else if ($(this).hasClass("denyFriendRequest")) {
//
} else {
//
}
}
You can do this:
$('#friendRequests').on('click', '[class$="FriendRequest"]', function (event) {
console.log(event.target.className);
}
Is there a way to run two functions similar to this:
$('.myClass').click(
function() {
// First click
},
function() {
// Second click
}
);
I want to use a basic toggle event, but .toggle() has been deprecated.
Try this:
$('.myClass').click(function() {
var clicks = $(this).data('clicks');
if (clicks) {
// odd clicks
} else {
// even clicks
}
$(this).data("clicks", !clicks);
});
This is based on an already answered question: Alternative to jQuery's .toggle() method that supports eventData?
Or this :
var clicks = 0;
$('.myClass').click(function() {
if (clicks == 0){
// first click
} else{
// second click
}
++clicks;
});
this I worked for my menu
var SubMenuH = $('.subBoxHederMenu').height();
var clicks = 0;
$('.btn-menu').click(function(){
if(clicks == 0){
$('.headerMenu').animate({height:SubMenuH});
clicks++;
console.log("abierto");
}else{
$('.headerMenu').animate({height:"55px"});
clicks--;
console.log("cerrado");
}
console.log(clicks);
});
i don't know what you are tryin to do but we can get basic toggle by
$('.myClass').click({
var $this=$(this);
if($this.is(':hidden'))
{
$this.show('slow');
}else{
$this.hide('slow');
}
})
note: this works for endless click event for that element .. not just for two clicks (if that is what you want)
OR you can use css class to hide/show the div and use jquery.toggleClass()
In the method mentioned below We are passing an array of functions to our custom .toggleClick() function. And We are using data-* attribute of HTML5 to store index of the function that will be executed in next iteration of click event handling process. This value, stored in data-index property, is updated in each iteration so that we can track the index of function to be executed in next iteration.
All of these functions will be executed one by one in each iteration of click event. For example in first iteration function at index[0] will be executed, in 2nd iteration function stored at index[1] will be executed and so on.
You can pass only 2 functions to this array in your case. But this method is not limited to only 2 functions. You can pass 3, 4, 5 or more functions in this array and they will be executed without making any changes in code.
Example in the snippet below is handling four functions. You can pass functions according to your own needs.
$.fn.toggleClick = function(funcArray) {
return this.click(function() {
var elem = $(this);
var index = elem.data('index') || 0;
funcArray[index]();
elem.data('index', (index + 1) % funcArray.length);
});
};
$('.btn').toggleClick([
function() {
alert('From Function 1');
}, function() {
alert('From Function 2');
}, function() {
alert('From Function 3');
}, function() {
alert('From Function 4');
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" class="btn">Click Me</button>
<button type="button" class="btn">Click Me</button>
If you literally only want the first and second click:
$('.myClass').one( 'click', function() {
// First click
$('.myClass').one( 'click', function() {
// Second click
});
);
var click_s=0;
$('#show_pass').click(function(){
if(click_s % 2 == 0){
$('#pwd').attr('type','text');
$(this).html('Hide');
}
else{
$('#pwd').attr('type','password');
$(this).html('Show');
}
click_s++;
});
When You click the selector it automatically triggers second and waiting for another click event.
$(selector).click(function(e){
e.preventDefault(); // prevent from Posting or page loading
//do your stuff for first click;
$(this).click(function(e){
e.preventDefault();// prevent from Posting or page loading
// do your stuff for second click;
});
});
I hope this was helpful to you..
I reach here looking for some answers, and thanks to you guys I´ve solved this in great manner I would like to share mi solution.
I only use addClass, removeClass and hasClass JQuery commands.
This is how I´ve done it and it works great:
$('.toggle').click(function() {
if($('.categ').hasClass("open")){
$('.categ').removeClass('open');
}
else{
$('.categ').addClass('open');
}
});
This way a class .open is added to the Html when you first clikc.
Second click checks if the class exists. If exists it removes it.
Normally you write a handler for a button click like this:
$(document).ready(function()
{
$("button").click(function()
{
doSomething();
});
});
But in the case of an event delegator, to respond to an event with a function such as this:
function doSomething(event)
{
if (ev.target.id == 'button1' )
{
//do your stuff
console.log('#button1 click');
}
else
{
console.log('not a #button1 click');
}
}
What I'm confused about is the correct syntax for defining the event that calls this delegator function - this? (A):
$(document).ready(function()
{
$(function()
{
$('button').click(doSomething);
});
});
or this? (B):
$(document).ready(function()
{
$("button").click(doSomething);
});
Which is correct and why?
In choice A you are just repeating the document.ready syntax twice.
// These two lines are equal
$(document).ready(fn);
$(fn);
All you need to do is choice B
While choice B would certainly be the way to do this if you needed to use a separate function, i.e., in the case where you needed to invoke the function from somewhere other than a button click, my preference is usually to put the code in line. The only other times I don't do this is when it would improve readability.
$(function() {
$("button").click( function(e) {
if (e.target.id == 'button1') {
alert('button1 clicked');
}
...
});
});