AngularJS, combine these two methods into one - javascript

I have a div
<div id="slideHolder" ng-mouseenter="fadeIn()" ng-mouseleave="fadeOut()">
...
</div>
And the content in the middle fades in an out on mouseenter/leave
$scope.fadeIn = function()
{
TweenLite.to("#zoomInButton",0.3,{opacity:1});
}
$scope.fadeOut = function()
{
TweenLite.to("#zoomInButton",0.3,{opacity:0});
}
Is it possible combine those two functions into one using an if statement ? I know how I'd do it in jQuery, but not sure how to in Angular. Thanks
Edit:
This is how I did it in jQuery
$("#slideHolder").hover(
function() {
$("#zoomButton").stop(true,true).fadeIn();
},
function() {
$("#zoomButton").stop(true,true).fadeOut();
}
);
Granted they are technically two function still, I was able to shorthand them into the hover method

I was able to figure this one out
<div id="slideHolder" ng-mouseenter="fade($event)" ng-mouseleave="fade($event)">
....
</div>
and in angular
$scope.fade = function(event)
{
(event.type == 'mouseover') ? TweenLite.to("#zoomInButton",0.3,{opacity:1}) : TweenLite.to("#zoomInButton",0.3,{opacity:0});
}

Related

Rewriting simple jquery code in angular style

I have a jquery code that checks for the class .slide on pageload. I have .slide classes inside my templates that it doesn't find and I am trying to figure out a way to make them find it. (probably by making a directive?)
If anyone has any ideas, I'd greatly appreciate it.
The code is as follows:
var items = $('.slide');
var content = $('.content');
function open() {
$(items).removeClass('close').addClass('open');
}
function close() {
$(items).removeClass('open').addClass('close');
}
$('#navToggle').on(clickevent, function(event) {
event.stopPropagation();
event.preventDefault();
if (content.hasClass('open')) {
close();
} else {
open();
}
});
content.click(function() {
if (content.hasClass('open')) {
close();
}
});
You can create a directive with the same name as your class name:
Say you have two spans with one you need to distinguish using class 'myclass':
<div ng-app="ClassExample" ng-controller="someController">
<span class="myclass myotherclass">target span</span><br/>
<span class="myotherclass">other span</span>
</div>
Then the accompanying js code would include a directive definition using the name of the class 'myclass' and you can restrict this directive to classes using restrict:'C' :
angular.module('ClassExample',[]).directive('myclass', function() {
return {
template:'hello world',
restrict: 'C'
};
}).controller('someController',function() {
});
Here is the fiddle: https://jsfiddle.net/1L3h8y7s/1/

Javascript ignoring if statements

I'm somewhat new to Javascript. I'm trying to make it so that clicking on an image on one page takes you to a new page and shows a specific div on that new page, so I used sessionStorage to remember and booleans to keep track of which image is being clicked. Right now, the code always executes the first if statement, regardless of which image is clicked. This code works fine in normal java so I can't figure out why my if statements are being ignored in javascript. I also tried adding an 'else' at the end, and tried ===. Here's my javscript, and thank you!
sessionStorage.clickedLeft;
sessionStorage.clickedMiddle;
sessionStorage.clickedRight;
function openedProjectFromGallery() {
if(sessionStorage.clickedLeft) {
$(".left-project-pop-up").show();
} else if (sessionStorage.clickedMiddle) {
$(".middle-project-pop-up").show();
} else if (sessionStorage.clickedRight) {
$(".right-project-pop-up").show();
}
sessionStorage.clickedLeft = false;
sessionStorage.clickedMiddle = false;
sessionStorage.clickedRight = false;
}
$("document").ready(function () {
$(".pop-up .x-button").click(function(){
$(".pop-up").hide();
});
$(".project-description .x-button").click(function(){
$(".project-pop-up").hide();
});
$(".left-project-thumb img").on("click", ".left-project-thumb img", function(){
sessionStorage.clickedLeft = true;
sessionStorage.clickedMiddle = false;
sessionStorage.clickedRight = false;
openedProjectFromGallery();
});
$(".profile-left-project img").click(function(){
$(".left-project-pop-up").show(1000);
});
$(".middle-project-thumb img").on("click", ".middle-project-thumb img", (function(){
sessionStorage.clickedMiddle = true;
sessionStorage.clickedLeft = false;
sessionStorage.clickedRight = false;
openedProjectFromGallery();
});
$(".profile-middle-project img").click(function(){
$(".middle-project-pop-up").show(1000);
});
$(".right-project-thumb img").on("click", ".right-project-thumb img", (function(){
sessionStorage.clickedRight = true;
sessionStorage.clickedLeft = false;
sessionStorage.clickedMiddle = false;
openedProjectFromGallery();
});
$(".profile-right-project img").click(function(){
$(".right-project-pop-up").show(1000);
});
});
You are defining function openedProjectFromGallery() with in document.ready . Define it outside document.ready and also give your three booleans some initial value at the top of your code if not initialized with some value or they are empty. I hope this would help.
It is not really answer to your orginal question,as the main issue with your code is, as #njzk2 says, that openProjectFromGallery only being called once, and not on each event, however I wanted to put my two coins on how this code could look like.
This is good example where custom events should be used
$(document).on('showPopup', function( e, popup ) {
$('.'+popup + '-project-pop-up').show()
})
$(document).on('hidePopup', function( e ) {
$('.popup').hide()
})
$('.left-project-thumb img').on('click', function(e) {
$(document).trigger('showPopup', ['left'])
})
$('.right-project-thumb img').on('click', function(e) {
$(document).trigger('showPopup', ['right'])
})
I think you get an idea.
On the other hand, it always nice to use event delegation with a lot of similar events as well as dom data.
<div class='popup' data-popup='left'>
<img />
</div>
$(document).on('click','.popup', function( e ) {
$(document).trigger('showPopup', [$(this).data('popup')])
})
From what I can see openedProjectFromGallery is only getting called on document load.
Add a call to it into each of the event handling functions or use jQuery's delegate function to assign event handling to each image.

Can I check if Bootstrap Modal Shown / Hidden?

Can I check if Bootstrap Modal currently Shown / Hidden Programatically?
Like bool a = if("#myModal").shown(); ?
I need true/false
alert($('#myModal').hasClass('in'));
It will return true if modal is open
The best method is given in the docs
$('#myModal').on('shown.bs.modal', function () {
// will only come inside after the modal is shown
});
for more info refer http://getbootstrap.com/javascript/#modals
its an old question but anyway heres something i used incase someone was looking for the same thing
if (!$('#myModal').is(':visible')) {
// if modal is not shown/visible then do something
}
All Bootstrap versions:
var isShown = $('.modal').hasClass('in') || $('.modal').hasClass('show')
To just close it independent of state and version:
$('.modal button.close').click()
more info
Bootstrap 3 and before
var isShown = $('.modal').hasClass('in')
Bootstrap 4
var isShown = $('.modal').hasClass('show')
When modal hide? we check like this :
$('.yourmodal').on('hidden.bs.modal', function () {
// do something here
})
Use hasClass('in'). It will return true if modal is in OPEN state.
E.g:
if($('.modal').hasClass('in')){
//Do something here
}
In offical way:
> ($("element").data('bs.modal') || {})._isShown // Bootstrap 4
> ($("element").data('bs.modal') || {}).isShown // Bootstrap <= 3
{} is used to avoid the case that modal is not opened yet (it return undefined). You can also assign it equal {isShown: false} to keep it's more make sense.
Here's some custom code that gives the modal states more explicitly named classes:
$('.modal').on('show.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-fading-in");
e.currentTarget.classList.remove("modal-fading-out");
e.currentTarget.classList.remove("modal-hidden");
e.currentTarget.classList.remove("modal-visible");
});
$('.modal').on('hide.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-fading-out");
e.currentTarget.classList.remove("modal-fading-in");
e.currentTarget.classList.remove("modal-hidden");
e.currentTarget.classList.remove("modal-visible");
});
$('.modal').on('hidden.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-hidden");
e.currentTarget.classList.remove("modal-fading-in");
e.currentTarget.classList.remove("modal-fading-out");
e.currentTarget.classList.remove("modal-visible");
});
$('.modal').on('shown.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-visible");
e.currentTarget.classList.remove("modal-fading-in");
e.currentTarget.classList.remove("modal-fading-out");
e.currentTarget.classList.remove("modal-hidden");
});
You can then easily target the modal's various states with both JS and CSS.
JS example:
if (document.getElementById('myModal').hasClass('modal-fading-in'))
{
console.log("The modal is currently fading in. Please wait.");
}
CSS example:
.modal-fading-out, .modal-hidden
{
opacity: 0.5;
}
With Bootstrap 4:
if ($('#myModal').hasClass('show')) {
alert("Modal is visible")
}
if($('.modal').hasClass('in')) {
alert($('.modal .in').attr('id')); //ID of the opened modal
} else {
alert("No pop-up opened");
}
For me this works
if($("#myModal").css("display") !='none' && $("#myModal").css("visibility") != 'hidden')
alert("modal shown");
I try like this with function then calling if needed a this function. Has been worked for me.
function modal_fix() {
var a = $(".modal"),
b = $("body");
a.on("shown.bs.modal", function () {
b.hasClass("modal-open") || b.addClass("modal-open");
});
}
This resolved your problems, if true no refresh, and false refresh
var truFalse = $('body').hasClass('modal-open');

Refactoring Code

Let's say I have the following code:
$(function () {
$(".buy-it-now.ribbon").click(function () {
$(".bid-to-beat.ribbon.active").removeClass("active");
$(".bid-to-beat.ribbon").addClass("inactive");
$(".buy-it-now.ribbon.inactive").removeClass("inactive");
$(".buy-it-now.ribbon").addClass("active");
$(".bid-now").hide();
$(".buy-now").show();
$(".add-to-cart").hide();
})
$(".bid-to-beat.ribbon").click(function () {
$(".buy-it-now.ribbon.active").removeClass("active");
$(".buy-it-now.ribbon").addClass("inactive");
$(".bid-to-beat.ribbon").removeClass("inactive");
$(".bid-to-beat.ribbon").addClass("active");
$(".buy-now").hide();
$(".bid-now").show();
$(".add-to-cart").show();
});
});
It is a simple function that allows for multiple UI related things to happen on the front-end of a site I am working on. I am fairly (very) new to jQuery and JavaScript in general and am learning about refactoring and making my code more condensed now. The way I currently write code is sort of line per thought I have. So my question is how would an experienced developer write this same code? Or rather, how could I refactor this code?
Try the following:
$(function () {
var $handlers = $('.buy-it-now.ribbon, .bid-to-beat.ribbon');
$handlers.click(function() {
$handlers.toggleClass("active inactive");
var $elements = $(".bid-now, .add-to-cart"),
$buyElement = $(".buy-now");
if($(this).is('.buy-it-now.ribbon')) {
$elements.hide();
$buyElement.show();
} else {
$elements.show();
$buyElement.hide();
}
});
});
This question would be better suited for codereview, but yes it can be condensed a little using method chaining.
$(function () {
$(".buy-it-now.ribbon").click(function () {
$(".bid-to-beat.ribbon").removeClass("active").addClass("inactive");
$(".buy-it-now.ribbon").removeClass("inactive").addClass("active");
$(".bid-now").hide();
$(".buy-now").show();
$(".add-to-cart").hide();
})
$(".bid-to-beat.ribbon").click(function () {
$(".buy-it-now.ribbon").removeClass("active").addClass("inactive");
$(".bid-to-beat.ribbon").removeClass("inactive").addClass("active");
$(".buy-now").hide();
$(".bid-now").show();
$(".add-to-cart").show();
});
});
You could condense it further by pre selecting the elements and caching them in variables before the click events as long as no elements are added or removed during the life of the page.
As your code it is you can combine some of the selectors into a single line. And also because your elements looks to be static you can cache them into a variable and use them later as it reduces the number of times a element is looked up in the DOM reducing the accessing time..
Also you can limit the scope of these variables or selectors by encasing them in an object or a closure..
Maybe something in these lines..
$(function () {
cart.init();
});
var cart = {
elems : {
$buyRibbon : null,
$bidRibbon : null,
$bidNow: null,
$buyNow: null,
$addToCart: null
},
events : {
},
init : function() {
this.elems.$buyRibbon = $(".buy-it-now.ribbon");
this.elems.$bidRibbon = $(".bid-to-beat.ribbon");
this.elems.$bidNow = $(".bid-now") ;
this.elems.$buyNow = $(".buy-now") ;
this.elems.$addToCart = $(".add-to-cart") ;
this.events.buyClick();
this.events.bidClick();
}
};
cart.events.buyClick = function() {
cart.elems.$buyRibbon.on('click', function(){
cart.elems.$bidRibbon.removeClass('active').addClass('inactive');
cart.elems.$buyRibbon.removeClass('inactive').addClass('active');
cart.elems.$bidNow.hide();
cart.elems.$buyNow.show();
cart.elems.$addToCart.hide();
});
}
cart.events.bidClick = function() {
cart.elems.$bidRibbon.on('click', function(){
cart.elems.$buyRibbon.removeClass('active').addClass('inactive');
cart.elems.$bidRibbon.removeClass('inactive').addClass('active');
cart.elems.$bidNow.show();
cart.elems.$buyNow.hide();
cart.elems.$addToCart.show();
});
}
So basically in here your whole cart is a object ..And the cart has different properties which are related to this.. You follow the principles of object oriented programming here..
Using closures I heard gives you better design limiting the scope of your code..
Might I suggest something like this:
$(function () {
var buyNowButton = $('buy-it-now.ribbon'),
bidToBeatButton = $('.bid-to-beat.ribbon'),
buyNowEls = $('.buy-now'),
bidToBeatEls = $('.bid-now,.add-to-cart');
var toggleButtons = function(showBuyNow){
buyNowButton.toggleClass('active', showBuyNow);
bidToBeatButton.toggleClass('active', !showBuyNow);
buyNowEls.toggle(showBuyNow);
bidToBeatEls.toggle(!showBuyNow);
}
buyNowButton.click(function(){ toggleButtons(true) });
bidToBeatButton.click(function(){ toggleButtons(false) });
});
You could save a some lines by removing the selectors at the start and just do the selection in place, if the saved space would be more important than the minor performance hit. Then it would look like this:
$(function () {
var toggleButtons = function(showBuyNow){
$('buy-it-now.ribbon').toggleClass('active', showBuyNow);
$('.bid-to-beat.ribbon').toggleClass('active', !showBuyNow);
$('.buy-now').toggle(showBuyNow);
$('.bid-now,.add-to-cart').toggle(!showBuyNow);
}
$('buy-it-now.ribbon').click(function(){ toggleButtons(true) });
$('.bid-to-beat.ribbon').click(function(){ toggleButtons(false) });
});
The first version selects the elements once and holds them in memory; the second selects them each time the button is clicked. Both solve the problem I believe would occur with the selected answer where clicking the same button twice would cause the .active and .inactive classes to get out of sync with the shown/hidden elements.

Need Help for better practice Jquery codes

I am trying to make my jquery codes look better here. My functions are working correctly but I was wondering if anyone can make my codes less ugly. Thanks a lot!
HTML
<div class='image_layout'>
<a href='#'><img src=' a.jpg '/></a>
<br><p class='credits'>hahahah
<br>Agency: Agency1
<br>Picture ID: 5 </p>
</div>
jQuery
$('#image_layout').on('hover', 'img', function() {
$(this).parent().next().next().fadeIn('fast');
})
$('#image_layout').on('mouseout', 'img', function() {
$(this).parent().next().next().fadeOut('fast');
})​
You can pass two functions to jQuery hover - one for mousein, one for mouseout. You can make this change as long as you don't have dynamically added images. Your code would also be a lot simpler if the element you are fading has an ID or class:
$('#image_layout img').hover(
function () {
$(this).closest('.someClass').fadeIn('fast');
},
function () {
$(this).closest('.someClass').fadeOut('fast');
}
);
$('.image_layout').on('hover', 'img', function (e) {
if(e.type == 'mouseover') {
$(this).closest('.image_layout').find('.credits').stop().fadeIn('fast');
} else {
$(this).closest('.image_layout').find('.credits').stop().fadeOut('fast');
}
})
You could also have done:
$('.image_layout').on('hover', 'img', function() {
$(this).closest('.image_layout').find('.credits').stop().fadeIn('fast');
}, function() {
$(this).closest('.image_layout').find('.credits').stop().fadeOut('fast');
});
If you're sure that nothing other than hovering the image will cause the element to fade, you could simply write:
$('.image_layout').on('hover', 'img', function() {
$(this).closest('.image_layout').find('.credits').stop().fadeToggle('fast');
});
Look into Douglas Crockford's JS Style Guide. He'd make your code look something like (with improvements):
var obj = $('#image_layout img');
obj.mouseover( function(){
$(this).parent([selector]).next([selector]).fadeIn('fast');
});
obj.mouseout( function(){
$(this).parent([selector]).next([selector]).fadeOut('fast');
});
You don't need the on, just call the function directly.
I would use .eq as opposed to two next statements, additionally, hover takes two functions, the first being for the mouseenter event, and the second for mouseout
$('#image_layout').hover('hover', 'img', function () {
$(this).parent().eq(2).fadeIn('fast');
}, function () {
$(this).parent().eq(2).fadeOut('fast');
})
References
Take a look at eq here
Read over hover here

Categories