jQuery: how $.on should work? - javascript

There is a site with one main index.html page (with <html><head>...) and pages like gallery.html, contacts.html, but only with <div> containers and without <html><head>....
So, when i click on index.html link to contacts.html what happens:
$('.contacts').click(function(e) {
e.preventDefault();
$('#content').load('contacts.html', function() {
.....
});
});
Q: How should i structure or organize javascript code for any events like click on contacts.html?
For example:
[1] I can write on contacts.html javascript code like:
<script type='text/javascript'>
$(function() {
$('.anyClassOnContactsHtml').click(function(e) {
.....
});
});
</script>
But as i guess, every time when i load contacts.html it reads the functions again and that is why the speed and performance of the site may be lower, because i have 50+ click events on every page.
[2] I can write on index.html delegates:
<script type='text/javascript'>
$(function() {
$('#content').on('click', '.anyClassOnContactsHtml', function(e) {
.....
});
});
</script>
It works and browsers read click functions 1 time, but with 100+ click functions there are 2-3 SECONDS (!) delay, so it works very slow.
To work it faster i should instead of #content write container that is nearer to my .anyClassOnContactsHtml, but i can't, because on index.html there are only #container.
So, how should i do? Or are there other ways to bind events? Any tips for site performance? Thank you.

1) You can actually call sub-elements that way.
${"#content .anyClassOnContactsHtml").click(function() {
});
2) Take a look at: http://developer.yahoo.com/yslow/. For example, placing <script> tags at the bottom of <body>
</body> will allow the rest of the page to load quicker.
Install the plugin and run the test on your page.

When you load() content, any code within loaded script tags is completely ignored, so it has no impact on javascript performance.
What might be the issue is that the way the content is loaded. Make sure you're not re-binding the click functions each time. Here is some example code:
<script type='text/javascript'>
$(function() {
$('.contacts').click(function(e) {
e.preventDefault();
$('#content').load('contacts.html', function() {
// DO NOT REBIND CLICK EVENTS HERE
});
});
// The following should only be done ONCE
$('#content').on('click', '.anyClassOnContactsHtml', function(e) {
.....
});
});
</script>

Is something like this really that slow?? I would say its should be okay!
<script type='text/javascript'>
$(function() {
$('.contacts').click(function(e) {
e.preventDefault();
$('#content').load('contacts.html', function() {
$('#content_of_loaded').on('click', '.anyClassOnContactsHtml', function(e) {
.....
});
});
});
});
</script>
Maybe you could also try this:
<script type='text/javascript'>
$(function() {
$('a').click(function(e) {
e.preventDefault();
var site = $(this).attr("href");
$('#content').load(site, function() {
$('#sub_content').on('click', '.anyClassOnContactsHtml', function(e) {
.....
});
});
});
});
</script>
and also for your subcontent links you could do this maybe..
function loadContent(site) {
$('#content').load(site, function() {
$('#sub_content').on('click', 'a', function(e) {
e.preventDefault();
loadContent($(this).attr("href"));
});
});
}
$(function() {
$('a').click(function(e) {
e.preventDefault();
loadContent($(this).attr("href"));
});
});
but i didnt test it, so might be wrong :)

I think the only way you are going to have any luck performance optimizing this is if you refactor some of your click functions to combine them and make them more multi-purpose by adding more method parameters, switch statements, etc... The most efficient way then would be to bind them all to #content since they won't have to be reloaded every time there is a URL change. The data attribute can help immensely with this. If you took the time to do it properly, you could even refactor all of your code into one event handler function.
A very contrived example of a function like this would be:
$('#content').on('click', 'a, span, input', function(e) {
var tagName = $(e.target).prop('tagName');
switch (tagName) {
case 'a':
processAnchorEvents();
break;
case 'span':
processSpanEvents();
break;
case 'input':
processInputEvents();
break;
}
});

Related

HTML Grid view and List View

So I want my contents to change its appearance depending on what button i click (grid view and list view) ..
I did some research and most of the stuff can be done using jquery. But i want to use only javascript.
My questions are:
what elements should i use? I am currently patterning (if this is even a real word) my app by using semantic ui.
I found this snippet here in stackoverflow http://jsfiddle.net/LJf9p/794/
but I can't seem to make it run, i mean it runs but it doesnt change appearance depending on button click if i put on html, do i have to add some more stuff? it works on the fiddle but not when i run it on my local browser. thanks
$('button').click(function(e) {
if ($(this).hasClass('grid')) {
$('#container ul').removeClass('list').addClass('grid');
}
else if($(this).hasClass('list')) {
$('#container ul').removeClass('grid').addClass('list');
}
});
please add
http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
and
$( document ).ready(function() { });
it works
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('button').click(function(e) {
if ($(this).hasClass('grid')) {
$('#container ul').removeClass('list').addClass('grid');
}
else if($(this).hasClass('list')) {
$('#container ul').removeClass('grid').addClass('list');
}
});
});
</script>

Minimise javascript code in html

I am working with jquery and multiple scripts that require javascript in the HTML document to function correctly (thankyou web 2.0). I am using ajax to post, $(document).ready to run functions and other multiple events etc. I am using googles minify to help the load time of the external javascript files required to run the javascript in the HTML. I am also having trouble structuring/formatting my javascript.
My questions are as follows:
How do I minimise the code in the HTML document?
Is it possible to link the javascript in the HTML document externally
even if it requires $(document).ready, like my example below?
What is a good site or tutorial to assist me in correctly formatting
my jquery/javascript as I am well aware this is incorrect and does this help load time?
Below is an example of a page where I run multiple scripts (feel free to format this correctly) and an example of what I would like to link externally and structure correctly. I am not asking for anyone to do my work for me but to simply just lead me in the right direction.
<script type="text/javascript" src="lib/js/jquery.nivo.slider.js"></script>
<script type="text/javascript" src="lib/js/jquery.fancybox.js"></script>
<script type="text/javascript" src="lib/js/jquery.jcarousel.min.js"></script>
<script type="text/javascript">
//nivo
$(window).load(function() {
$('#slider').nivoSlider({ effect: 'slideInLeft', pauseTime: 5000 });
});
//fancybox
$(document).ready(function() {
$('.fancybox').fancybox();
$.fancybox.open($("#welcome"), { padding : 0 });
});
//subscribe
$("#footer-subscribe-show-hide").click(function () {
$("#footer-subscribe").animate({width:'toggle'},300);
$(this).show("#subscribe");
});
//responsive
$(function() {
$('.menu-mobile-drop').click(function() {
$('.menu-mobile').toggle();
});
});
$(".menu-wrap").click(function() {
$(this).find('img').toggle();
});
//subscriptionAjax
$("#subscriber").submit(function(event) {
event.preventDefault();
$("#footer-subscribe").fadeOut();
var values = $(this).serialize();
$.ajax({
url: "include/subscribe.php",
type: "post",
data: values,
success: function(){
$("#footer-subscribe")
.html(
"<div class='subscription-success'>You're now subscribed!</div>"
)
.fadeIn('slow');
},
error: function(){
alert("failure");
$("#footer-subscribe").html('there is error while submit');
}
});
});
//jcarousel
function mycarousel_initCallback(carousel) {
carousel.clip.hover(function() {
carousel.stopAuto();
},
function() {
carousel.startAuto();
});
};
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel({
auto: 8,
wrap: 'last',
initCallback: mycarousel_initCallback
});
});
</script>
To minimize JavaScript in HTML, simply keep all of it out of HTML.
If you need something scripted on a page, you should add a <script src=""></script> element. There's no reason to include any raw javascript on the page directly.
If you need to select an element, make good use of [data-*] attributes, selectors, and iteration:
$('[data-foo]').each(function () {
var $this,
data;
$this = $(this);
data = $this.data('foo');
$this.foo(data);
});
How do I minimise the code in the HTML document?
Inline javascript code such as
<script>
$(function () {
alert("Hello World");
});
</script>
can be minified by using a service (e.g. Google Closure Compiler). You can simply copy and paste your code to the UI and get the minified version.
Is it possible to link the javascript in the HTML document externally even if it requires $(document).ready, like my example below?
Yes that is certainly possible. You just need to be aware of the loading order:
<script>
$(function () {
alert("Hello World");
});
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
This will not work because you are calling the document.ready function from jQuery before actually including the library.
What is a good site or tutorial to assist me in correctly formatting my jquery/javascript as I am well aware this is incorrect and does this help load time?
I will recommend using PageSpeed (available as a Chrome / Firefox extension) for analyzing potential performance issues. This extension automatically generates useful suggestions (e.g. Load order of scripts/stylesheets) that will certainly increase your web application's performance.
You don't have to put your JavaScript into your HTML page. Just include it using the <script> tag.
If you really want to go deep in increasing the page load time, you can use something like Minify to compress your JS and CSS code.
jQuery offers two powerful methods to execute code and attach event handlers: $(document).ready and $(window).load. The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place.
More more detail refer this post..
jQuery events .load(), .ready(), .unload()
Try this for your answer:
<script type="text/javascript" src="lib/js/jquery.nivo.slider.js"></script>
<script type="text/javascript" src="lib/js/jquery.fancybox.js"></script>
<script type="text/javascript" src="lib/js/jquery.jcarousel.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//nivo
$('#slider').nivoSlider({ effect: 'slideInLeft', pauseTime: 5000 });
//fancybox
$('.fancybox').fancybox();
$.fancybox.open($("#welcome"), { padding : 0 });
//subscribe
$("#footer-subscribe-show-hide").click(function () {
$("#footer-subscribe").animate({width:'toggle'},300);
$(this).show("#subscribe");
});
$('.menu-mobile-drop').click(function() {
$('.menu-mobile').toggle();
});
$(".menu-wrap").click(function() {
$(this).find('img').toggle();
});
//subscriptionAjax
$("#subscriber").submit(function(event) {
event.preventDefault();
$("#footer-subscribe").fadeOut();
var values = $(this).serialize();
$.ajax({
url: "include/subscribe.php",
type: "post",
data: values,
success: function(){
$("#footer-subscribe")
.html(
"<div class='subscription-success'>You're now subscribed!</div>"
)
.fadeIn('slow');
},
error: function(){
alert("failure");
$("#footer-subscribe").html('there is error while submit');
}
});
});
//jcarousel
function mycarousel_initCallback(carousel) {
carousel.clip.hover(function() {
carousel.stopAuto();
},
function() {
carousel.startAuto();
});
};
$('#mycarousel').jcarousel({
auto: 8,
wrap: 'last',
initCallback: mycarousel_initCallback
});
});
</script>

window.onload function doesn't work on Mozilla Firefox

I'm using a loading screen for a webpage and I use window.onload function.
Everything works great except in Mozilla Firefox browsers. When we first visit or refresh the page with ctrl+F5 combination, the loading screen never disappears. if we refresh the page only with F5, then it works.
I use the code below
$(window).load(function(e) {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
});
I have also tried the code below but nothing changed.
window.onload = function () {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
}
Why this is happening?
Please help.
Thanks in advance.
The problem is caused by another jquery background plugin which is placed inside $(document).ready()
I moved it inside $(window).load() function, now it works perfect.
I have also moved another function to resize images on the page load. When it was inside $(document).ready() block, sometimes it was malfunctioning if loading time took too long but now it also works great.
function resizeImages(){
//Some Code
}
$(window).load(function(){
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
$.vegas({
src: backURL , fade:0
});
resizeImages();
});
$(document).ready(function(){
//Some Other code
});
I got the same problem when mistyped the type attribute in the script tag:
<script type="text/javascript">
Try This:
$(document).ready(function(e) {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
});
Read for load and ready functions difference What is the difference between $(window).load and $(document).ready?
You must call function on initialization like :
window.onload = init();
in other word modify your code to:
window.onload = function () {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
}();// Added
Copy following code in file then open it with firefox
<script>
window.onload = function () {
alert('saeed')
}();
</script>

simulating a click on a <a>-element in javascript

for a website, i am using the jQuery supzersized gallery script: http://buildinternet.com/project/supersized/slideshow/3.2/demo.html
As you can see in the demo, in the bottom right corner there is an little arrow button that toggles a thumbnail bar. There is no option in the config files to automatically blend this in when opening the site.
So i guess i have to simulate a click on that button (the button is the tray-button, see HTML). I tried something like this:
<script>
$(function() {
$('#tray-button').click();
});
</script>
However, this doesnt seem to work in any browsers i tested.
Any idea?
$('#tray-arrow').click(function() {
// prepare an action here, maybe say goodbye.
//
// if #tray-arrow is button or link <a href=...>
// you can allow or disallow going to the link:
// return true; // accept action
// return false; // disallow
});
$('#tray-arrow').trigger('click'); // this is a simulation of click
Try this
$("#tray-arrow").live("click", function () {
// do something
});
I assume that you want to popup the thumbnail bar #thump-tray on page load.
Here's a way to do it:
locate the file supersized.shutter.js and find this code:
// Thumbnail Tray Toggle
$(vars.tray_button).toggle(function(){
$(vars.thumb_tray).stop().animate({bottom : 0, avoidTransforms : true}, 300 );
if ($(vars.tray_arrow).attr('src')) $(vars.tray_arrow).attr("src", vars.image_path + "button-tray-down.png");
return false;
}, function() {
$(vars.thumb_tray).stop().animate({bottom : -$(vars.thumb_tray).height(), avoidTransforms : true}, 300 );
if ($(vars.tray_arrow).attr('src')) $(vars.tray_arrow).attr("src", vars.image_path + "button-tray-up.png");
return false;
});
After it, add:
$(vars.tray_button).click();
Dont forget in your page (demo.html in the plugin), to change
<script type="text/javascript" src="theme/supersized.shutter.min.js"></script>
to
<script type="text/javascript" src="theme/supersized.shutter.js"></script>
instead of using
$(function(){
//jquery magic magic
});
you culd try this witch will work your jquery magic after the full page is loaded (images etc)
$(window).load(function () {
// jquery magic
});
and to simulate a click you culd use // shuld be the same as $('#tray-arrow').click();
$('#tray-arrow').trigger('click',function(){ })
example:
$(window).load(function () {
$('#tray-arrow').trigger('click',function(){
alert('just been clicked!');
})
});
try
<script>
$(function() {
$('#tray-arrow').click();
});
</script>
Make sure that this code is after your carousel is initialized.
This looks like it's a problem of timing the trigger. The plugin also loads on document load, so maybe when you try to bind the event listener the element is not created yet.
Maybe you need to add the listener in something like the theme._init function
http://buildinternet.com/project/supersized/docs.html#theme-init
or somewhere similar.
A problem might be that your plugin detects whether the click has been initiated by a user (real mouse click), or through code (by using $('#id').click() method). If so, it's natural that you can't get any result from clicking the anchor element through code.
Check the source code of your plugin.

Script does not work when on <head>

I proved script. its works, but outside of .
I am not good on script. maybe its a simple problem.
<head>
<script src="http://code.jquery.com/jquery-1.5.js" type="text/javascript"></script>
<script src="http://0rochymugen.ucoz.com/scriptbestsite.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
basicly, script just show a when a mouse its over to image.
$('#img1').mouseover(function () {
$('#p1').show("slow");
});
$("#p1").hover(function () {
$("#p1").hide("slow");
});
when I put script on head. simply, doesnt work.
In some cases, if you are trying to operate on items that are on the page, if you javascript loads and executes before the rest of the page has finished loading, you will get errors and/or your code will not appear to work.
This is one reason it is recommended to put links to javascript files at the bottom of the page.
Another good practice is to only run your when the document has finished loading, in jQuery is is normally done using the following syntax:
$(document).ready(function(){
// Your javascript
}
I think your code doesn't work because you're not running it when document's ready:
$(document).ready(function(){
$('#img1').mouseover(function () {
$('#p1').show("slow");
});
$("#p1").hover(function () {
$("#p1").hide("slow");
});
$("#img2").mouseover(function () {
$('#p2').show("slow");
});
$("#p2").hover(function () {
$("#p2").hide("slow");
});
$("#img3").mouseover(function () {
$('#p3').show("slow");
});
$("#p3").hover(function () {
$("#p3").hide("slow");
});
$("#img4").mouseover(function () {
$('#p4').show("slow");
});
$("#p4").hover(function () {
$("#p4").hide("slow");
});
$("#img5").mouseover(function () {
$('#p5').show("slow");
});
$("#p5").hover(function () {
$("#p5").hide("slow");
});
});
Also you can pass two functions two your hover handler to handle both mouseover and mouseout events. I think that'll shorten your code a bit. ;)
The problem is that the elements you are referencing, don't exist yet.
To ensure they exist before using them, you have to put it's related code inside $(document).ready. So you have:
$(document).ready(function(){ //This ensures DOM elements are loaded
$('#img1').mouseover(function () {
$('#p1').show("slow");
});
$("#p1").hover(function () {
$("#p1").hide("slow");
});
});
But, if you can't change that js file, to add a document.ready, you could load the script dynamically, as the following:
<head>
...
<script type="text/javascript">
$(document).ready(function(){
$.getScript("http://0rochymugen.ucoz.com/scriptbestsite.js");
});
</script>
...
</head>
It's not mandatory for the js scripts (in general) to be on the head section, but it's a good practice IMHO. However, other people prefer to put it at the bottom of the page for performance reasons.
Hope this helps.

Categories

Resources