div equal height animation on document ready - html

I have a script called equal-heights.js which works together with underscore.js. It equalize the divs to the size of the highest div with an animation (optional). The problem is that when I charge the page nothing happens, it starts to equalize the divs only when I resize the browser.
The initialising code on the HTML:
$(document).ready(function() {
$('.profile-panel').equalHeights({
responsive:true,
animate:true,
animateSpeed:500
});
});
You can see the equal-heights.js here: http://webdesign.igorlaszlo.com/templates/js/blogger-equal-heights-responsive.js
What should I do so that, when the page loads, the animation starts to equalize the divs automatically?

I created my own test and realized the issue is with the way the plugin has been written, namely that it only accepts one value for the class name, otherwise it will break.
This is because of the following line in the script:
className = '.'+$(this).prop('class');
What this does is that it takes the class property of your element and adds a dot (.) in front; a nice but not very scalable way of getting the current selector, because if you have multiple class names, it will only put a dot in front of the first one, so if you have...
<div class="profile-panel profile-panel-1st-row profile-panel1">
...it will transform it into...
$('.profile-panel profile-panel-1st-row profile-panel1')
...so understandably this will not work properly, as the dots are missing from the rest of the classes.
To go around this, until version 1.7, jQuery had a .selector property, that however has now been deprecated. Instead they're now suggesting to add the selector as an argument of your plugin's function as follows (and I tailored it to your situation):
First define an option called selector when calling the function:
$('.profile-panel-1st-row').equalHeights({
selector:'.profile-panel-1st-row',
// ...
});
Then setup the className variable inside the plugin as follows:
var className = options.selector;
Another thing you can do is the place the class you're using to activate the plugin as the first one for each element you want to use it on, so instead of...
<div class="profile-panel profile-panel-1st-row profile-panel1">
...do this...
<div class="profile-panel-1st-row profile-panel profile-panel1">
...then you can setup the className variable inside the plugin as follows:
var className = '.'+ $(this).prop('class').split(" ").slice(0,1);
This basically splits the class names into parts divided by space and takes the first one.
To have the best of both solutions, simply set className to the following:
var className = options.selector || '.'+ $(this).prop('class').split(" ").slice(0,1);
As to the animation, it only works on resize; that is intended, that's how the plugin has been built, you can play around with the original example of the plugin creator that I added to jsfiddle: http://jsfiddle.net/o9rjvq8j/1/
EDIT #2: If you're happy to change the plugin even more, just remove $(window).resize(function() in the if(settings.responsive === true) check and you'll have it working. ;)
if(settings.responsive === true) {
//reset height to auto
$(className).css("height","auto");
//re initialise
reInit();
}

Related

Polymer - cloneNode including __data

I am using the library dragula for doing some drag & drop stuff.
Dragula internally uses cloneNode(true) to create a copy of the dragged element that will be appended to the body to show the preview image while dragging.
Unfortunately, if dragging a polymer element, the bound data get's not cloned. By consequence the contents of the dragged element (e.g. <div>[[someString]]</div>) are empty.
Is there a solution for this?
I actually do not need the data to be bound for my element, it is just a "read-only" element that displays some data that does not change after being initialized. Is there maybe a way to somehow "resolve" the strings to the html without being bound anymore?
Thank you already!
Found a solution myself. You have to override the cloneNode method inside the polymer class:
cloneNode(deep) {
let cloned = super.cloneNode(deep);
for (let prop in MyClass.properties) {
cloned[prop] = this[prop];
}
return cloned;
}

How to access more than 2 DOM elements "The AngularJS way"?

I'm starting to learn angularJS better, and I've noticed that AngularJS tries to make strong emphasis on separating the view from the controller and encapsulation. One example of this is people telling me DOM manipulation should go in directives. I kinda got the hang of it now, and how using link functions that inject the current element allow for great behavior functionality, but this doesn't explain a problem I always encounter.
Example:
I have a sidebar I want to open by clicking a button. There is no way to do this in button's directive link function without using a hard-coded javascript/jquery selector to grab the sidebar, something I've seen very frowned upon in angularJS (hard-coding dom selectors) since it breaks separation of concerns. I guess one way of getting around this is making each element I wish to manipulate an attribute directive and on it's link function, saving a reference it's element property into a dom-factory so that whenever a directive needs to access an element other than itself, it can call the dom-factory which returns the element, even if it knows nothing where it came from. But is this the "Angular way"?
I say this because in my current project I'm using hard-coded selectors which are already a pain to mantain because I'm constantly changing my css. There must be a better way to access multiple DOM elements. Any ideas?
There are a number of ways to approach this.
One approach, is to create a create a sidebar directive that responds to "well-defined" broadcasted messages to open/close the sidebar.
.directive("sidebar", function(){
return {
templateUrl: "sidebar.template.html",
link: function(scope, element){
scope.$root.$on("openSidebar", function(){
// whatever you do to actually show the sidebar DOM content
// e.x. element.show();
});
}
}
});
Then, a button could invoke a function in some controller to open a sidebar:
$scope.openSidebar = function(){
$scope.$root.$emit("openSidebar");
}
Another approach is to use a $sidebar service - this is somewhat similar to how $modal works in angularui-bootstrap, but could be more simplified.
Well, if you have a directive on a button and the element you need is outside the directive, you could pass the class of the element you need to toggle as an attribute
<button my-directive data-toggle-class="sidebar">open</button>
Then in your directive
App.directive('myDirective', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
angular.element('.' + attrs.toggleClass).toggleClass('active');
}
};
}
You won't always have the link element argument match up with what you need to manipulate unfortunately. There are many "angular ways" to solve this though.
You could even do something like:
<div ng-init="isOpen = false" class="sidebar" ng-class="{'active': isOpen}" ng-click="isOpen = !isOpen">
...
</div>
The best way for directive to communicate with each other is through events. It also keeps with the separation of concerns. Your button could $broadcast on the $rootScope so that all scopes hear it. You would emit and event such as sidebar.open. Then the sidebar directive would listen for that event and act upon it.

How to correctly call jQuery function that uses HTML elements?

I'm new to the use of jQuery so the problem I'm facing should be fairly straight forward. Basically what I'm trying to accomplish is load a variety of simple text-only pages within DIV elements of my site, and with a navigation bar hide/unhide these individual DIVs.
DIVs are correctly loaded the requested pages using an script block. However, what is not working correctly is toggling the visibility of these DIV blocks. I've narrowed it down to a jQuery function I've created which blocks the entire script call whenever I refer to any of the DIV blocks. Let me explain better with a code snippet.
This is is some very simple code that, on the click of a menu link, runs a hide function then shows the corresponding DIV element.
$( document ).ready(function()
{
console.log("document ready."); <-- does NOT get called with hideDivs()
$('#button1').click(function(){
hideDivs();
$("#page1").show();
});
$('#button2').click(function(){
hideDivs();
$("#page2").show();
});
});
This is the hideDivs() function, JUST above the ready function:
function hideDivs()
{
$("#page1").hide(); <-- These lines cause the entire
$("#page2").hide(); <-- <script> block to note get called.
}
Finally, page1 and page2 are created with a script block halfway inside the page:
<div id="page1"></div>
<div id="page2"></div>
<script>
$("#page1").html('<object style="overflow:hidden; width: 100%; height: 500px;" data="page1.php">').show();
$("#page2").html('<object style="overflow:hidden; width: 100%; height: 500px;" data="page2.php">').hide();
</script>
Why then is it that the top SCRIPT block fails with the hideDivs() function? I've tried placing it inside the $( document ).ready function with no change. Again, if the function is blank, or contains something simple like 'console.log' it works, but when referring to DIV tags it breaks.
Even stranger, the code that makes the function FAIL, WORKS if I simply rewrite the code as such:
$('#button1').click(function(){
$("#page1").hide(); <-- This works fine
$("#page2").hide(); <-- (page1 repeated to match function code)
$("#page1").show();
});
I have quite a few pages so I would much rather be able to use a function as not to have lots of repetitive code.
I have no errors displayed in my javascript console. I've looked closely at functions calls with StackOverflow and Google searches but couldn't spot a solution. I'm sure I've made a really silly mistake I'm overlooking, so any help would be much appreciated.
So instead of the whole function to hide your divs, you can simply put a class on each one and hide them by selecting that class. For example, each page Div give a class="clickablePages", and then do:
$(".clickablePages").hide();
that will simply hide all the divs that you have added the class to.
As for repeating all the button clicks for each button, you can simply do it in one function based on the id of the button. You can again put a class on all of the buttons as well, trigger the function by selecting the class and then grab the id you need within that function. something like this:
$('.buttonclick').click(function(){
var pageID = $(this).attr('id');
$("#page" + pageID).show();
});
In this case, if your buttons just had an id of '1' or '2' that matched the page number, it would only show the div for that page number. Hope that makes sense.

Binding to events on parent page from iframe [duplicate]

I have an iframe and in order to access parent element I implemented following code:
window.parent.document.getElementById('parentPrice').innerHTML
How to get the same result using jquery?
UPDATE: Or how to access iFrame parent page using jquery?
To find in the parent of the iFrame use:
$('#parentPrice', window.parent.document).html();
The second parameter for the $() wrapper is the context in which to search. This defaults to document.
how to access iFrame parent page using jquery
window.parent.document.
jQuery is a library on top of JavaScript, not a complete replacement for it. You don't have to replace every last JavaScript expression with something involving $.
If you need to find the jQuery instance in the parent document (e.g., to call an utility function provided by a plug-in) use one of these syntaxes:
window.parent.$
window.parent.jQuery
Example:
window.parent.$.modal.close();
jQuery gets attached to the window object and that's what window.parent is.
You can access elements of parent window from within an iframe by using window.parent like this:
// using jquery
window.parent.$("#element_id");
Which is the same as:
// pure javascript
window.parent.document.getElementById("element_id");
And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:
// using jquery
window.top.$("#element_id");
Which is the same as:
// pure javascript
window.top.document.getElementById("element_id");
in parent window put :
<script>
function ifDoneChildFrame(val)
{
$('#parentPrice').html(val);
}
</script>
and in iframe src file put :
<script>window.parent.ifDoneChildFrame('Your value here');</script>
yeah it works for me as well.
Note : we need to use window.parent.document
$("button", window.parent.document).click(function()
{
alert("Functionality defined by def");
});
It's working for me with little twist.
In my case I have to populate value from POPUP JS to PARENT WINDOW form.
So I have used $('#ee_id',window.opener.document).val(eeID);
Excellent!!!
Might be a little late to the game here, but I just discovered this fantastic jQuery plugin https://github.com/mkdynamic/jquery-popupwindow. It basically uses an onUnload callback event, so it basically listens out for the closing of the child window, and will perform any necessary stuff at that point. SO there's really no need to write any JS in the child window to pass back to the parent.
There are multiple ways to do these.
I) Get main parent directly.
for exa. i want to replace my child page to iframe then
var link = '<%=Page.ResolveUrl("~/Home/SubscribeReport")%>';
top.location.replace(link);
here top.location gets parent directly.
II) get parent one by one,
var element = $('.iframe:visible', window.parent.document);
here if you have more then one iframe, then specify active or visible one.
you also can do like these for getting further parents,
var masterParent = element.parent().parent().parent()
III) get parent by Identifier.
var myWindow = window.top.$("#Identifier")

mootools - using addEvent to element not working properly?

bangin' my head against this and it's starting to hurt.
I'm having trouble with adding an event to an element.
I'm able to add the event, and then call it immediately with element.fireEvent('click'), but once the element is attached to the DOM, it does not react to the click.
example code:
var el = new Element('strong').setStyle('cursor','pointer');
el.addEvent('click',function () { alert('hi!'); });
el.replaces(old_element); // you can assume old_element exists
el.fireEvent('click'); // alert fires
however, once I attach this to the DOM, the element is not reactive to the click. styles stick (cursor is pointer when I mouseover), but no event fires. tried mouseover as well, to no avail.
any clues here? am I missing something basic? I am doing this all over the place, but in this one instance it doesn't work.
EDIT----------------
ok here's some more code. unfortunately I can't expose the real code, as it's for a project that is still under tight wraps.
basically, the nodes all get picked up as "replaceable", then the json found in the rel="" attribute sets the stage for what it should be replaced by. In this particular instance, the replaced element is a user name that should pop up some info when clicked.
again, if I fire the event directly after attaching it, all is good, but the element does not react to the click once it's attached.
HTML-----------
<p>Example: <span class='_mootpl_' rel="{'text':'foo','tag':'strong','event':'click','action':'MyAction','params':{'var1': 'val1','var2': 'val2'}}"></span></p>
JAVASCRIPT-----
assumptions:
1. below two functions are part of a larger class
2. ROOTELEMENT is set at initialize()
3. MyAction is defined before any parsing takes place (and is properly handled on the .fireEvent() test)
parseTemplate: function() {
this.ROOTELEMENT.getElements('span._mootpl_').each(function(el) {
var _c = JSON.decode(el.get('rel'));
var new_el = this.get_replace_element(_c); // sets up the base element
if (_c.hasOwnProperty('event')) {
new_el = this.attach_event(new_el, _c);
}
});
},
attach_event: function(el, _c) {
el.store(_c.event+'-action',_c.action);
el.store('params',_c.params);
el.addEvent(_c.event, function() {
eval(this.retrieve('click-action') + '(this);');
}).setStyle('cursor','pointer');
return el;
},
Works just fine. Test case: http://jsfiddle.net/2GX66/
debugging this is not easy when you lack content / DOM.
first - do you use event delegation or have event handlers on a parent / the parent element that do event.stop()?
if so, replace with event.preventDefault()
second thing to do. do not replace an element but put it somewhere else in the DOM - like document.body's first node and see if it works there.
if it does work elsewhere, see #1
though I realsie you said 'example code', you should write this as:
new Element('strong', {
styles: {
cursor: "pointer"
},
events: {
click: function(event) {
console.log("hi");
}
}
}).replaces(old_element);
no point in doing 3 separate statements and saving a reference if you are not going to reuse it. you really ought to show the ACTUAL code if you need advice, though. in this snippet you don't even set content text so the element won't show if it's inline. could it be a styling issue, what is the display on the element, inline? inline-block?
can you assign it a class that changes it on a :hover pseudo and see it do it? mind you, you say the cursor sticks which means you can mouseover it - hence css works. this also eliminates the possibility of having any element shims above it / transparent els that can prevent the event from bubbling.
finally. assign it an id in the making. assign the event to a parent element via:
parentEl.addEvent("click:relay(strong#idhere)", fn);
and see if it works that way (you need Element.delegate from mootools-more)
good luck, gotta love the weird problems - makes our job worth doing. it wouldn't be the worst thing to post a url or JSFIDDLE too...