Where to place JQuery (set :visibility via CSS) in a BackBone View - javascript

I think this question ultimately boils down to where I should place the JQuery code, and I am unsure for backbone.js.
I have a nested div :
<div>Parent
<div class='pull-right remove-measure-btn'>Child</div>
</div>
and I want the child to only show when the parent is being hovered.
So I can use this code (top lines within the func() in the render() of the parent Backbone.View.extend:
render: function():
....
$(this.el).hover(
function() {
$('.remove-measure-btn').show();
// $('.remove-measure-btn').css('visibility' : 'visible');
},
function() {
$('.remove-measure-btn').hide();
// $('.remove-measure-btn').css('visibility' : 'hidden');
}
);
....
return this;
},
But this only toggles the display, and since I am using Bootstrap and taking advantage of .pull-right, I need to toggle CSS' :visibility, and not display: to keep the height of the child div in place when it is not visible. So if I use the second line from within the above code block, I get an undefined error, since the compiled template has been returned yet (i think....).
So where do I place the JQuery to change the CSS visibilty, or how do I change the rendering to accomodate the code where it is?
Notes:
There are many of these "parent" and "child" divs.
I am assuming it is best to use the selector with this.el to tie the interaction directly as opposed to using several global document.ready()s, but maybe I am not aware of a "safe/good" way to accomplish it using this method

As chcrist notes, the "Backbone" way of doing this is to use the events hash:
var MyView = Backbone.View.extend({
events: {
'mouseenter': 'showChild',
'mouseleave': 'hideChild'
},
render: function () {
//...
},
showChild: function () {
$('.remove-measure-btn').css({'visibility' : 'visible'});
},
hideChild: function () {
$('.remove-measure-btn').css({'visibility' : 'hidden'});
}
});
Also, I'm assuming this is a typo, but this code is wrong:
$('.remove-measure-btn').css('visibility' : 'hidden');
You can either pass an object (one or more style properties):
$('.remove-measure-btn').css({'visibility' : 'hidden'});
Or pass one property/value pair:
$('.remove-measure-btn').css('visibility', 'hidden');

This can be done with straight CSS. Javascript (backbone or otherwise) is not required.
Adding the following CSS to your page will get you exactly what you need without the use of javascript:
.remove-measure-btn {
visibility:hidden;
}
div:hover > .remove-measure-btn {
visibility:visible;
}
A fiddle showing this in action is here: http://jsfiddle.net/35TXY/

try $('remove-measure-button').addClass('hidden') and removeClass('hidden'). Define hidden:
.hidden {visibility: hidden;}

Related

calling a template helper function from inside a template event callback

I am very new to meteor and it is possible that I am going about this entirely incorrectly.
I have a simple template that represents a menu bar. When the user clicks an Icon, the menu is supposed to appear. When they click it again, it is supposed to disappear.
Here is the markup:
<template name="menu">
<div class="menu">
<div class="toggler">
<i class="fa fa-bars fa-3x"></i>
</div>
<div class="menu-body">
<!-- ... -->
</div>
</div>
</template>
Here is the JS that I have:
Template.menu.helpers({
self: Template.instance(),
menu_body: self.find('.menu-body'),
toggler: self.find('.toggler'),
currently_open: false,
open: function() {
menu_body.style.display = 'flex';
},
close: function() {
menu_body.style.display = 'none';
},
toggle: function() {
if(currently_open) close();
else open();
}
});
Template.menu.events({
'click .toggler': function(event, template) {
console.log(template);
template.toggle();
}
});
I thought the template instance would have access to the helper functions, but according to the log statement, this is what the template instance consists of:
B…e.TemplateInstance {view: B…e.View, data: null, firstNode: div.menu, lastNode: div.menu, _allSubsReadyDep: T…r.Dependency…}
_allSubsReady: false
_allSubsReadyDep: Tracker.Dependency
_subscriptionHandles: Object
data: null
firstNode: div.menu
lastNode: div.menu
view: Blaze.View
__proto__: Blaze.TemplateInstance
Can someone point me in the right direction here. Please feel free to be scrutinous if I am going about it wrong.
Helpers are for functional calls - not event driven works.
Meteor has an events handle that you can use to track events like clicks. Also you can use your css classes to define the styles nicely without programatically overwriting them.
Template.name.events({
'click .menuToggler': function(event, template) {
event.preventDefault();
var menu = template.find('.menu-body'); //(make this in ID!)
if($(menu).hasClass('menuOpen')) {
$(menu).removeClass('menuOpen');
//menu.style.display = 'none';
} else {
$(menu).addClass('menuOpen');
//menu.style.display = 'flex'; Use css to define these on the menuOpen class
}
});
Some things to note: This event handle assumes that your menu-body class is available under the template called "name" in my example. So you will want this event handler at the most top level template you have. It also assumes.
If you want to share state between the various components of your template (helpers, event callbacks etc) it should be done by setting properties directly on the template instances.
This can be done through the onCreated() callback
As per the documentation:
Callbacks added with this method [are] called before your template's logic
is evaluated for the first time. Inside a callback, this is the new
template instance object. Properties you set on this object will be
visible from the callbacks added with onRendered and onDestroyed
methods and from event handlers.
These callbacks fire once and are the first group of callbacks to
fire. Handling the created event is a useful way to set up values on
template instance that are read from template helpers using
Template.instance().
So, to provide a more relevant and concise example than the one in my original question.
Template.menu.onCreated(function() {
this.items = [
{title: 'Home', icon: 'home'},
{title: 'Profile', icon: 'user'},
{title: 'Work', icon: 'line-chart'},
{title: 'Contact', icon: 'phone'}
];
});
Template.menu.helpers({
items: function() {
var self = Template.instance();
return self.items;
}
});
Template.menu.events({
'click .toggler': function(event, template) {
console.log(template.items); //[Object,Object,Object,Object]
//do something with items
}
});
That's actually funny but I created a mini package that helps you do just that: https://atmospherejs.com/voidale/helpers-everywhere
But in your case it's not the right way of doing it. I can you see you want to add an display either flex or none it's better add CSS element like active that hold display: flex and add active or remove it on click like this: $('').addClass('active') or $().removeClass('active')
one liner can also work here: $('.menu-body').toggleClass('active')

How do I apply jQuery's slideToggle() to $(this) and do the opposite to all other elements?

What I'd like to do is have all elements of class collapsible_list not displayed by default (with one exception... see below*), and then toggle their display when their parent <div class="tab_box"> is clicked. During the same click, I'd also like for every other element of class collapsible_list to be hidden so that only one of them is expanded at any given time.
*Furthermore, when the page initially loads I'd also like to check to see if an element of collapsible_list has a child a element whose class is activelink, and if there is one then I'd like that link's parent collapsible_list element to be the one that's expanded by default.
Here's some sample html code:
<style>
.collapsible_list {
display: none;
}
.collapsible_list.active {
display: block;
}
</style>
<div id="sidebar">
<div class="tab_box">
<div class="collapsible_tab">2014</div>
<div class="collapsible_list panel-2014">
1
2
3
</div>
</div>
<div class="tab_box">
<div class="collapsible_tab">2013</div>
<div class="collapsible_list panel-2013">
<a class="activelink" href="/2013/1">1</a>
2
3
</div>
</div>
</div>
And here's where I'm currently at with the javascript (although I've tried a bunch of different ways and none have worked like I'd like them to):
$(document).ready(function() {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active");
$(".tab_box").click(function() {
$(this).children(".collapsible_list").toggleClass("active").slideToggle("slow", function() {
$(".collapsible_list.active:not(this)").each(function() {
$(this).slideToggle("slow");
});
});
});
});
I hope that's not too confusing, but if it is then feel free to let me know. Any help is much appreciated.
Since you have a dom element reference that needs to be excluded use .not() instead of the :not() selector
jQuery(function ($) {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active").show();
$(".tab_box").click(function () {
var $target = $(this).children(".collapsible_list").toggleClass("active").stop(true).slideToggle("slow");
//slidup others
$(".collapsible_list.active").not($target).stop(true).slideUp("slow").removeClass('active');
});
});
Also, instead of using the slide callback do it directly in the callback so that both the animations can run simultaniously
Also remove the css rule .collapsible_list.active as the display is controlled by animations(slide)
Try This.
$('.collapsible_tab a').on('click', function(e){
e.preventDefault();
$('.collapsible_list').removeClass('active')
$(this).parent().next('.collapsible_list').toggleClass('active');
});
Fiddle Demo
I think your code would be less complicated if you simply remembered the previously opened list:
jQuery(function($) {
// remember current list and make it visible
var $current = $('.collapsible_list:has(.activelink)').show();
$(".tab_box").on('click', function() {
var $previous = $current;
// open new list
$current = $('.collapsible_list', this)
.slideToggle("slow", function() {
// and slide out the previous
$previous.slideToggle('slow');
});
});
});
Demo

how to repeat same Javascript code over multiple html elements

Note: Changed code so that images and texts are links.
Basically, I have 3 pictures all with the same class, different ID. I have a javascript code which I want to apply to all three pictures, except, the code needs to be SLIGHTLY different depending on the picture. Here is the html:
<div class=column1of4>
<img src="images/actual.jpg" id="first">
<div id="firsttext" class="spanlink"><p>lots of text</p></div>
</div>
<div class=column1of4>
<img src="images/fake.jpg" id="second">
<div id="moretext" class="spanlink"><p>more text</p></div>
</div>
<div class=column1of4>
<img src="images/real.jpg" id="eighth">
<div id="evenmoretext" class="spanlink"><p>even more text</p></div>
</div>
Here is the Javascript for the id="firsttext":
$('#firstextt').hide();
$('#first, #firsttext').hover(function(){
//in
$('#firsttext').show();
},function(){
//out
$('#firsttext').hide();
});
So when a user hovers over #first, #firsttext will appear. Then, I want it so that when a user hovers over #second, #moretext should appear, etc.
I've done programming in Python, I created a sudo code and basically it is this.
text = [#firsttext, #moretext, #evenmoretext]
picture = [#first, #second, #eighth]
for number in range.len(text) //over here, basically find out how many elements are in text
$('text[number]').hide();
$('text[number], picture[number]').hover(function(){
//in
$('text[number]').show();
},function(){
//out
$('text[number]').hide();
});
The syntax is probably way off, but that's just the sudo code. Can anyone help me make the actual Javascript code for it?
try this
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink").show();
});
Why not
$('.spanlink').hide();
$('.column1of4').hover(
function() {
// in
$(this).children('.spanlink').show();
},
function() {
// out
$(this).children('.spanlink').hide();
}
);
It doesn't even need the ids.
You can do it :
$('.column1of4').click(function(){
$(this); // the current object
$(this).children('img'); // img in the current object
});
or a loop :
$('.column1of4').each(function(){
...
});
Dont use Id as $('#id') for multiple events, use a .class or an [attribute] do this.
If you're using jQuery, this is quite easy to accomplish:
$('.column1of4 .spanlink').hide();
$('.column1of4 img').mouseenter(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').show();
});
$('.column1of4 img').mouseleave(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').hide();
});
Depending on your markup structure, you could use DOM traversing functions like .filter(), .find(), .next() to get to your selected node.
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink, img").show();
});
So, the way you would do this, given your html would look like:
$('.column1of4').on('mouseenter mouseleave', 'img, .spanlink', function(ev) {
$(ev.delegateTarget).find('.spanlink').toggle(ev.type === 'mouseenter');
}).find('.spanlink').hide();
But building on what you have:
var text = ['#firsttext', '#moretext', '#evenmoretext'];
var picture = ['#first', '#second', '#third'];
This is a traditional loop using a closure (it's better to define the function outside of the loop, but I'm going to leave it there for this):
// You could also do var length = text.length and replace the "3"
for ( var i = 0; i < 3; ++i ) {
// create a closure so that i isn't incremented when the event happens.
(function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(',')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
})(i);
}
And the following is using $.each to iterate over the group.
$.each(text, function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(', ')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
});
Here's a fiddle with all three versions. Just uncomment the one you want to test and give it a go.
I moved the image inside the div and used this code, a working example:
$('.column1of4').each(function(){
$('div', $(this)).each(function(){
$(this).hover(
function(){
//in
$('img', $(this)).show();
},
function(){
//out
$('img', $(this)).hide();
});
});
});
The general idea is 1) use a selector that isn't an ID so I can iterate over several elements without worrying if future elements will be added later 2) locate the div to hide/show based on location relational to $(this) (will only work if you repeat this structure in your markup) 3) move the image tag inside the div (if you don't, then the hover gets a little spazzy because the positioned is changed when the image is shown, therefore affecting whether the cursor is inside the div or not.
EDIT
Updated fiddle for additional requirements (see comments).

hide one div when another is showing in jQuery?

I am trying to hide a div when another one is visible.
I have div 1 and div 2.
If div 2 is showing then div 1 should hide and if div 2 is not showing then div 1 should be visible/unhide.
The function would need to be function/document ready upon page load.
I've tried this but I'm not having any luck, can someone please show me how I can do this.
<script>
window.onLoad(function () {
if ($('.div2').is(":visible")) {
$(".div1").fadeOut(fast);
} else if ($('.div2').is(":hidden")) {
$('.div1').fadeIn(fast);
}
});
</script>
Add a class of hidden to each div, then toggle between that class using jQuery. By the way, window.onload is not a function, it expects a string like window.onload = function() {}. Also, put fast in quotations. I don't know if that's required, but that's how jQuery says to do it.
<div class="div1"></div>
<div class="div2 hidden"></div>
.hidden { display: none }
$(document).ready(function() {
if($(".div1").hasClass("hidden")) {
$(".div2").fadeIn("fast");
}
else if($(".div2").hasClass("hidden")) {
$(".div1").fadeIn("fast");
}
});
You should pass a string to the .fadeIn() and .fadeOut() methods.
Instead of .fadeIn(fast) it'll be .fadeIn("fast"). Same for .fadeOut().
And in general since you're already using jQuery it's better to wrap your code like this:
$(function () {
// Code goes here
});
It looks like you're using jquery selectors (a javascript library). If you're going to use jquery make sure the library is loaded properly by including it in the document header (google makes this easy by hosting it for you <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>)
With jQuery loaded you can do it like this
$(document).ready(function(){
if ($('.div1').is(":visible")) {
$('div2').hide();
}
else if ($('.div2').is(":visible")) {
$('div1').hide();
}
});
WORKING EXAMPLE: http://jsfiddle.net/HVDHC/ - just change display:none from div 2 to div 1 and click 'run' to see it alternate.
You can use setTimeout or setInterval to track if these divs exists
$(function() {
var interval = window.setInterval(function() {
if($('#div2').hasClass('showing')) {
$('#div1').fadeOut('fast');
}
if($('#div2').hasClass('hidden')) {
$('#div1').fadeIn('fast');
}
}, 100);
// when some time u don't want to track it
// window.clearInterval(interval)
})
for better performance
var div1 = $('#div1')
, div2 = $('#div2')
var interval ....
// same as pre code

combining a method to hide or show content

I was wondering how I can combine a hide function and show function into 1 toggle Function that either fades in content or fades it out, im guessing this argument would update the fade method:
This is my current effort of JS using jQuery from my object but is totally wrong:
toggleAlertOverlay: function (state) {
var instance = this;
if (state === hide) {
instance.selector.fadeOut();
}
elseif(state === show) {
instance.selector.fadeIn();
}
},
toggleAlertOverlay(hide);
Try using .fadeToggle()
The .fadeToggle() method animates the opacity of the matched elements. When called on a visible element, the element's display style property is set to none once the opacity reaches 0, so the element no longer affects the layout of the page.
$(<element>).fadeToggle();
Where <element> is a valid selector ....
var toggleState = 'none';
toggleAllertOverlay: function()
{
if(toggleState == 'none')
{
$('#element').fadeIn();
toggleState == 'showing';
}
else
{
$('#element').fadeOut();
toggleState == 'none';
}
}
is just a concept based on what you have. Note the variable outside of the function. Its outside so it doesn't get destroyed upon function complete. But aside from that, theres various other methods you can try if this doesn't suit you. Up to and including jQuery toggle()

Categories

Resources