I've been coding my own dialog system for exercising and to be able to customize it as i want. Here is what i've done.
$(function(){
$.fn.window = function(attr){
var $self = this;
if(!attr)
attr = {};
$.extend({
autoOpen:false
}, attr);
/**
* Create the window by updating the current jQuery block
* And adding the required classes
*/
this.create= function(){
// Already created
if($self.hasClass('window-window'))
return;
$self.addClass('window-window');
// Creating the header and appending the title
var $windowHeader = $('<div class="window-header"></div>');
var $title = $self.attr('title');
$windowHeader.html($title);
$windowHeader.append('<div class="loading-item loading-item-footer round-loading25" ' +
'data-loading-item="window" style="display:none"></div>');
// Wrapping content in a window-content class
// So the window has the proper format
$self.children().wrapAll('<div class="window-content"></div>');
$self.prepend($windowHeader);
};
/**
* Open the window in a blackish div
* With the events to close it
*/
this.open = function(){
// Creating the background
var $backgroundDiv = $('<div></div>');
$backgroundDiv.addClass('window-background');
// Making it take the size of the page
$backgroundDiv.height($(window).height());
$backgroundDiv.width($(window).width());
$self.detach().appendTo($backgroundDiv);
// The window is hidden by default, showing it
$self.show();
$('html').prepend($backgroundDiv);
// Handling closing the window
$backgroundDiv.click(function(e){
var $target = $(e.target);
if(!$target.hasClass('window-background'))
return;
$self.hide();
$self.detach().appendTo('html');
$backgroundDiv.remove();
});
};
this.create();
if(attr.autoOpen){
this.open();
}
};
});
For now i have doubt about the fact that i'm putting the window out of his native block, in the end of the html document. I wish to put it back to his position but i have no idea yet how to do it. Any idea ?
First of all, you create a jQuery function, but you do it on document.ready $(...). You should just create it, otherwise the function will not be available for other code until document has loaded.
Then you want to insert the window in the same place as the original element, for that you have insertBefore and insertAfter in jQuery. You use prepend, but that inserts it as the first element of $self.
I would urge you to look at the method chaining of jQuery which may make your code much more readable. Instead of:
// Creating the background
var $backgroundDiv = $('<div></div>');
$backgroundDiv.addClass('window-background');
// Making it take the size of the page
$backgroundDiv.height($(window).height());
$backgroundDiv.width($(window).width());
use
// Creating the background
var $backgroundDiv = $('<div></div>')
.addClass('window-background')
// Making it take the size of the page
.css({
height:$(window).height(),
width:$(window).width()
});
for example.
You also use CSS classes to store information, like if something had been clicked or not. That may be OK, but consider that you may want change the CSS classes and suddenly the functionality of your code is strongly linked to the design. Maybe using .data() instead would be better, even if you add more code to also style your elements.
You use .wrap to take the original content and put it in the window. That may be what you wanted all along, but also take a look at https://api.jquery.com/clone/ which allows you to get the elements without removing them from their original source. Again, only if it works better for you.
As a last advice, use http://jsfiddle.net to share your working code, so other people may not only comment on it, but see it in action as well.
Related
I have a list composed by some divs, all of them have a info link with the class .lnkInfo. When clicked it should trigger a function that adds the class show to another div (like some sort of PopUp) so it is visible and when clicked again it should hide it.
I am quite certain this must be a very basic thing and most likely I will get some scoffs...but hey! Once I have this down that's one thing less I will ever have to ask again. Anyway I am starting to leave the safety of html and css to start learning JS, PHP and the like and I came to a bit of a problem.
When testing it before it was working, that was until I added another div, it only worked with the first one, reading a bit and with some suggestion I realized it must be something related to a array, the problem is that I am not quite certain of the syntax for accomplishing what I am visualizing.
Any help would be deeply appreciated.
This is my JS code and below I will attack a Fiddle of how the html looks just in case.
var infoLab = document.getElementsByClassName('lnkInfo'),
closeInfo = document.getElementById('btnCerrar');
infoLab.addEventListener('click', function () {
for (var i = 0 ; i < infoLab.length; i++) {
var links = infoLab[i];
displayPopUp('popUpCorrecto1', 'infoLab[i]');
};
});
function displayPopUp(pIdDiv, infoLab[i]){
var display = document.getElementById(pIdDiv),
for (var i = 0 ; i < infoLab.length; i++) {
infoLab[i]
newClass ='';
newClass = display.className.replace('hide','');
display.className = newClass + ' show';
};
}
JSFiddle.
Thanks a lot in advance and sorry for any facepalms!
EDIT:
This a jQuery function (in another file) that I need to call using the link because it fetches the data that will be inside the div, thus why I wanted to just add a hide/show.
$(".lnkInfo").click(function() {
var id = $('#txtId').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'displayInfoLabs',
'pId':id},
dataType: 'html',
success: function(response){
$('#info').html(response);
}
});
});
EDIT 2:
To a future reader of this question,
If you managed to find this answer throughout space and time, know that this is how the solution ended being, may it help you in your quest to stop being a noob.
SOLUTION
Here is a rudimentary working example of how to make a popup appear after clicking on a specific element given your current code. Note that I added an id to your link element.
// Select the element.
var infoLink1 = document.getElementById('infoLink1');
// Add an event listener to that element.
infoLink1.addEventListener('click', function () {
displayPopUp('popUpCorrecto1');
});
// Display a the popup by removing it's default "hide"
// class and adding a "show" class.
function displayPopUp(pIdDiv) {
var display = document.getElementById(pIdDiv);
var newClass = display.className.replace('hide', '');
display.className = newClass + ' show';
}
Fiddle.
There are various ways to generalize this to work for all links/popups. You could add a data-link-number=1, data-link-number=2, etc to each link element (more on data-). Select an element containing all of your links. Bind to that element an event listener that, when clicked, detects the link element that was clicked (see event delegation / "bubbling"). You can determine which link was clicked based on the value of your data-link-number attribute. Then show the appropriate popup.
You may also want to use jQuery for this. Changing an element's class by setting it's className property makes for brittle DOM code. There is an addClass and a removeClass method available. jQuery's events also work cross-browser; element.addEventListener() will not work in IE8 which still has a significant market share.
The title of the question expresses what I think is the ultimate question behind my particular case.
My case:
Inside a click handler, I want to make an image visible (a 'loading' animation) right before a busy function starts. Then I want to make it invisible again after the function has completed.
Instead of what I expected I realize that the image never becomes visible. I guess that this is due to the browser waiting for the handler to end, before it can do any redrawing (I am sure there are good performance reasons for that).
The code (also in this fiddle: http://jsfiddle.net/JLmh4/2/)
html:
<img id="kitty" src="http://placekitten.com/50/50" style="display:none">
<div>click to see the cat </div>
js:
$(document).ready(function(){
$('#enlace').click(function(){
var kitty = $('#kitty');
kitty.css('display','block');
// see: http://unixpapa.com/js/sleep.html
function sleepStupidly(usec)
{
var endtime= new Date().getTime() + usec;
while (new Date().getTime() < endtime)
;
}
// simulates bussy proccess, calling some function...
sleepStupidly(4000);
// when this triggers the img style do refresh!
// but not before
alert('now you do see it');
kitty.css('display','none');
});
});
I have added the alert call right after the sleepStupidly function to show that in that moment of rest, the browser does redraw, but not before. I innocently expected it to redraw right after setting the 'display' to 'block';
For the record, I have also tried appending html tags, or swapping css classes, instead of the image showing and hiding in this code. Same result.
After all my research I think that what I would need is the ability to force the browser to redraw and stop every other thing until then.
Is it possible? Is it possible in a crossbrowser way? Some plugin I wasn't able to find maybe...?
I thought that maybe something like 'jquery css callback' (as in this question: In JQuery, Is it possible to get callback function after setting new css rule?) would do the trick ... but that doesn't exist.
I have also tried to separte the showing, function call and hiding in different handlers for the same event ... but nothing. Also adding a setTimeout to delay the execution of the function (as recommended here: Force DOM refresh in JavaScript).
Thanks and I hope it also helps others.
javier
EDIT (after setting my preferred answer):
Just to further explain why I selected the window.setTimeout strategy.
In my real use case I have realized that in order to give the browser time enough to redraw the page, I had to give it about 1000 milliseconds (much more than the 50 for the fiddle example). This I believe is due to a deeper DOM tree (in fact, unnecessarily deep).
The setTimeout let approach lets you do that.
Use JQuery show and hide callbacks (or other way to display something like fadeIn/fadeOut).
http://jsfiddle.net/JLmh4/3/
$(document).ready(function () {
$('#enlace').click(function () {
var kitty = $('#kitty');
// see: http://unixpapa.com/js/sleep.html
function sleepStupidly(usec) {
var endtime = new Date().getTime() + usec;
while (new Date().getTime() < endtime);
}
kitty.show(function () {
// simulates bussy proccess, calling some function...
sleepStupidly(4000);
// when this triggers the img style do refresh!
// but not before
alert('now you do see it');
kitty.hide();
});
});
});
Use window.setTimeout() with some short unnoticeable delay to run slow function:
$(document).ready(function() {
$('#enlace').click(function() {
showImage();
window.setTimeout(function() {
sleepStupidly(4000);
alert('now you do see it');
hideImage();
}, 50);
});
});
Live demo
To force redraw, you can use offsetHeight or getComputedStyle().
var foo = window.getComputedStyle(el, null);
or
var bar = el.offsetHeight;
"el" being a DOM element
I do not know if this works in your case (as I have not tested it), but when manipulating CSS with JavaScript/jQuery it is sometimes necessary to force redrawing of a specific element to make changes take effect.
This is done by simply requesting a CSS property.
In your case, I would try putting a kitty.position().left; before the function call prior to messing with setTimeout.
What worked for me is setting the following:
$(element).css('display','none');
After that you can do whatever you want, and eventually you want to do:
$(element).css('display','block');
I'm building my first js/jQuery site and I've run into a hiccup. I'm trying to use both jScrollpane (Kelvin Luck) and scrollTo (Ariel Flesler) plugins in one script. If I comment one out, the other works. Are they mutually exclusive? Do I need to unbind functionality out of jScrollpane to remove a 'scrollTo' call conflict or something? (I have no idea how to do that).
I'm using jScrollPane 2beta11 and scrollTo 1.4.2. Here's my stripped-down code using both:
// JavaScript Document
$(document).ready(function() {
//jScrollPane Init
$('#scrollingDiv').jScrollPane({
});
//scrollTo Refresh
$('div.scroll-pane').scrollTo( 0 );
$.scrollTo( 0 );
//Buttons
var $scrollDiv = $('#scrollingDiv');
var next = 1;
$('#but-rt').click(function(){
$scrollDiv.stop().scrollTo( 'li:eq(1)', 800 );
next = next + 1;
});
});
I'm aware that jScrollPane has it's own scrollTo functionality, but I need scrollTo's jQuery Object selectors in my particular project. I know I've got my HTML/CSS lined up fine because each function works as long as the other is commented out.
(By the way, I plan on using "next" variable to increment scrollTo button once I figure out how... not related to my problem tho.)
Any help is much appreciated. Let me know if there's anything else I need to supply. Thanks!
-Patrick
See how to use ScrollTo functionality of JscrollPane from the following url,
http://jscrollpane.kelvinluck.com/scroll_to.html
Hope this will help you...
I too was trying to use both jScrollpane (Kelvin Luck) and scrollTo (Ariel Flesler) plugins in one script. I've come across an easy solution which doesn't even require Ariel Flesler's AWESOME Script, if you don't necessarily require animated scrolling.
I wanted to be able to scroll to a label in a list of items when the page loads.
Here's how i did it:
$(function()
//Declare the ID or ClassName of the Scroll Element
//and the ID or ClassName of the label to scroll to
MyList = $('#MyElementID OR .MyElementClassName');
MyLabel = $('#MyElementID OR .MyElementClassName');
// Initiate the Scrollpane
MyScroll = $(MyList).jScrollPane();
// Connect to the jScrollPaneAPI
jScrollPaneAPI = MyScroll.data('jsp');
// Get position co-ordinates of the Label
var MyLabelPosition = $(MyLabel).position();
// Convert position co-ordinates to an Integer
MyLabelPosition = Math.abs(MyLabelPosition.top);
// Scroll to the Label (0-x, vertical scrolling) :)
jScrollPaneAPI.scrollTo(0, MyLabelPosition-3, true);
});
There's a small bug with the exact positioning when a list gets longer,
will post a fix asap...
They are mutually exclusive because jScrollPane removes the real scrolling and replaces it with complex boxes-in-boxes being moved relative to each other via JS.
This is how I successfully mixed them -- I had a horizontal list of thumbnails; this code scrolled the thumbnails to the center:
Activated jScrollPane:
specialScrolling = $('#scrollingpart').jScrollPane();
In my serialScroll code, where I usually would call
$('#scrollingpart').trigger('goto', [pos]);
in my case, inside my
onBefore:function(e, elem, $pane, $items, pos)
I put code like this:
jScrollPaneAPI = specialScrolling.data('jsp');
//get the api to manipulate the special scrolling are
scrollpos=(Math.abs(parseInt($('.jspPane').css('left'), 10)));
//get where we are currently scrolled -- since this is a negative number,
//get the absolute value
var position = $('#scrollingpart .oneitem').eq(pos).position();
//get the relative offset location of the item we are targetting --
//note "pos" which is the index number for the items that you can access
//in serialScroll's onBefore:function
itempos=Math.abs(position.left);
//get just the x-axis location -- your layout might be different
jScrollPaneAPI.scrollBy(itempos-scrollpos-480, 0, true);
//the 480 worked for my layout; the key is to subtract the 2 values as above
Hope this helps someone out there!
This doesn't cater for all use cases (it only handles scrollToY and scrollToElement), but offers a consistent API so you can just use $( /* ... */ ).scrollTo( /* number or selector */ ) and it will work on any element, jScrollPane or native.
You could extend the method condition to cater for all the other jScrollPane methods by inferring the value passed in target though.
(function scrollPaneScrollTo(){
// Save the original scrollTo function
var $defaultScrollTo = $.fn.scrollTo;
// Replace it with a wrapper which detects whether the element
// is an instance of jScrollPane or not
$.fn.scrollTo = function $scrollToWrapper( target ) {
var $element = $( this ),
jscroll = $element.data( 'jsp' ),
args = [].slice.call( arguments, 0 ),
method = typeof target === 'number' ? 'scrollToY' : 'scrollToElement';
if ( jscroll ) {
return jscroll[ method ].call( $element, target, true );
}
else {
return $defaultScrollTo.apply( $element, args );
}
};
}();
I have a site that features a "fixed" header, the problem is that it really messes up links that link further down the page a la "http://mysite.com/#lower_div_on_the_page"
Is it even possible to use javascript to do something like
if (URL has #hashtag) {starting scroll position = normal position + (my_header_height)}
Is this even possible?
EDIT:
Thanks for all the replies... really appreciated. For reference, I am DEFINITELY using jQuery... how would I do this with jQuery?
Yes, it's possible.
Here are the steps you need to take:
Set up a DOM Loaded event handler. There's more than one way to do this and here's a link to a web page that explains how to do this. Also if you're using a javascript framework such as jQuery (see .ready()) or Prototype.js (see observe extension) it would be a lot easier.
In the DOM loaded event handler function parse the URL (window.location) for the hashtag.
var hashTag = window.location.href;
hashTag = hashTag.substr(hashTag.indexOf('#') + 1);
// now hashTag contains the portion of the URL after the hash sign
Then if you recognize the anchor tag compute the desired scroll location based on that element's location in the DOM tree or whatever logic you would like to use. Again, jQuery (see .offset()) or Prototype.js (see cumulativeScrollOffset) should be able to help with determining the correct offset to scroll to.
Set the scroll of the page. Again jQuery (see .scrollTop()) or Prototype.js (see scrollTo) both have extensions to help with this.
Here's a jQuery example:
$(document).ready(function() {
var hashTag = window.location.href;
if(hashTag.indexOf('#') > 0)
{
hashTag = hashTag.substr(hashTag.indexOf('#'));
// now get the element's offset relative to the document
var offsetTop = $(hashTag).offset().top;
// and finally, scroll the document to that offset
$(document).scrollTop(offsetTop);
}
});
Sure is, you could do something as simple as:
if(window.location.hash != ''){
elementOffset = document.getElementById(window.location.hash.substr(1)).offsetTop;
window.scrollTo(0,elementOffset + my_header_height);
}
Using jQuery it'd obviously be simpler, and you would need to get extra offset depending on containing elements and such, but that should get you started.
My page adds # to the html programatically and have this in the tag
function InsertTag(){
//Add <a name="spot"></a> to the middle of this document
}
window.addEventListener('load', InsertTag, false);
my question is how can I make the document then jump to #spot?
Here's a suggestion: use id's instead. If you have:
<div id="something">
Then page.html#something will take you straight to that div. It doesn't have to be a div, it can be used on any element. If you can manipulate the DOM to add that anchor, I am pretty sure you'll be able to do this.
Now... To get there, you can use:
// this approach should work with anchors too
window.location.hash = 'something';
// or scroll silently to position
var node = document.getElementById('something');
window.scroll(0, node.offsetTop);
See it in action here: http://ablazex.com/demos/jump.html
There are subtle differences between the methods. Eg: The first one will cause the location on the address bar to be updated, the second one won't.
If you want it to look nicer you can use a jQuery plugin, like ScrollTo.
Try
window.location = currentUrl+'#spot';
where currentUrl is a variable having the address of the current url
You can try this.
var el = document.getElementById('spot');
var eloffsetTop = el.offsetTop;
window.scroll(0,eloffsetTop);