How do I inherit jQuery effects when i introduce a new DOM - javascript

I have a slideshow that i replace an unordered list within the slide show, the images change but any effects are not inherited. this is the script that introduces a new DOM:
jQuery("#kwick1").click(function () {
jQuery('#photography').load('/design.html #photography');
});
jQuery("#kwick2").click(function () {
jQuery('#photography').load('/design.html #design');
});
how do i get the jQuery slideshow to inherit this new list of images??
i both these functions and the slide show function in the same file.
I have a
jQuery(document).ready(function() {
that loads the slideshow script.

You have to let us know what slideshow plugin you are using. Regardless, you probably just need to destroy your old slideshow instance and restart it. Something like:
//start slideshow on
var slideshow = $('#slideshow').cycle();
slideshow.start();
$('#button').click( function() {
//depending on plugin api maybe stop, add and start again
slideshow.stop();
slideshow.addImages();
slideshow.start();
//or perhaps just destroy old slideshow and restart
slideshpw = $('#slideshow').cycle();
});

To attach events to newly added elements you should use live() or delegate();
jQuery('.yourselector').live('click', function(){
//do something on click
});

Instead of attaching events to each of elements, you should learn how to use event delegation. That way you can attach single event listener on some container ( or even document ) and catch the events as they bubble up.
Additionally it will make your code look much cleaner and easier to understand.
http://lab.distilldesign.com/event-delegation/
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-event-delegation-in-4-minutes/
http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/
P.S. , if you put your code at the bottom of the HTML ( before </body> ) then, when it triggers , it will already be an "onDomReady" event.

Related

How to dynamically add an ondragstart event to a dynamically created div

There are a couple of questions that seem to ask this question, but no one accepted answers and nothing has worked for me.
I have a 'group' button that when it's clicked, will dynamically create a 'group' div (I then append some pre-selected 'child' divs within it)
However I need the new 'group' div to be draggable.
I can set the draggable attribute dynamically, no problem.
But being draggable is not much good without the ondragstart() event, and no matter what I've tried, I can't get this assigned.
I am using jQuery which may have a bearing.
The latest iteration of my code is (this appears in an init() function that is called from body.onload):
var group=$(document.createElement('div'));
group.attr({id: 'group'+grpcount});
group.attr({draggable: "true"});
group.addClass('group');
group.html("<span class='group'>Group"+grpcount+"</span>");
$('#boundary').append(group);
document.getElementById('group'+grpcount).addEventListener("startdrag",drag);
But I have also tried various combinations of jQuery .bind:
group.bind("dragstart", drag(ev));
group.bind("dragstart", function(ev){drag(ev);});
All to no avail.
I have a drag function already defined (and I've tried putting it before and after the code above):
function drag(ev) {
ev.dataTransfer.setData("Text",ev.target.id+":"+ev.pageX+":"+ev.pageY);
}
I hope there is something glaringly obvious that I just can't see.
Can somebody solve this?
You'll be better to take a look at Jquery UI draggable here
and if you dont know yet, you can call multiple jquery finctions in a chain, so your code looks more readable like below:
var group=$('div').attr('id', 'group'+grpcount)
.addClass('group')
.html("<span class='group'>Group"+grpcount+"</span>");
$('#boundary').append(group);
and instead of
document.getElementById('group'+grpcount).addEventListener("startdrag",drag);
use this
group.draggable({
start:function(event, ui){
//this is where dragging starts when you push mousedown and move mouse
},
drag:function(event, ui){
//this function will be called after drag started each time you move your mouse
}
stop:function(event, ui){
//this is where you release mouse button
}
})
this jquery draggable widget with droppable widget will ease your life if you really want to implement complex drag-and-drop functionality
I made this:
function drag(ev) { alert('Hi'); }
var grpcount = 21;
var group=$(document.createElement('div'));
group.attr({id: 'group'+grpcount});
group.attr({draggable: "true"});
group.addClass('group');
group.html("<span class='group'>Group"+grpcount+"</span>");
group.bind("dragstart", function(ev){drag(ev);});
$('#boundary').append(group);
See the working fiddle here: http://jsfiddle.net/nxcSz/

Using Javascript/JQuery Mouseover fades in Firefox (keeps repeating)

I am trying to use JS/JQuery to make tiles that will fade out then fade in with different data (In this case it is pictures) when you over on it and then reverse it when you mouse off of it. Now my code works fine in Chrome but when I test it in FireFox it keeps executing the fade in/out commands. I looked up similar situations where people use the $(this).stop().fadeOut(function() code but since I am doing multiple fades and loading information it won't do the animation correctly. Does anyone know a solution to this?
<script>
$(document).ready(function()
{
var hov = false;
$(".previewBox").mouseenter(function()
{
if(hov === false)
{
hov = true;
$(this).fadeOut(function()
{
$(this).load(function()
{
$(this).fadeIn();
});
$(this).attr("src", "Images/Portfolio/Art_Bike_Flip.png");
});
};
});
$(".previewBox").mouseleave(function()
{
if(hov === true)
{
hov = false;
$(this).fadeOut(function()
{
$(this).load(function()
{
$(this).fadeIn();
});
$(this).attr("src", "Images/Portfolio/Art_Bike_Preview.png");
});
};
});
});
</script>`enter code here`
There are several problems here. First .load is not a reliable way to detect image loading. Some browsers, when the image is cached, wont fire a load event, so the script will fail. You need to use a plugin like waitForImages or imageLoaded.
https://github.com/alexanderdickson/waitForImages I recommend this one.
Also .stop() will work fine for your needs, if it seems to cancel fades in some instances, try .stop(true, true), it should animate just fine, even with loading data and multiple fades. You may need to tune it so that the stop command only is placed on the last fade to occur.
also you are making a ton of jQuery objects when you only need one. Limiting it to one object will make your script substantially more efficient.
var previewBox = $('.previewBox');
Then you can use that one everywhere:
previewBox.mouseenter(function()
{
if(hov === false)
{
hov = true;
previewBox.stop().fadeOut(function(){
previewBox.imagesLoaded(function...
In your case with the multiple instances using a class, you need to isolate your events from one another. You can do this with .each
$('.previewBox').each(function(){
var previewBox = $(this);
previewBox.mouseenter(function(){ ....
By wrapping all your current logic in a .each you will avoid interaction of events between elements. In this way the events mouseenter mouseleave and the attached logic will bind isolated to each instance of an element with that class, instead of binding to all elements of that class.

jqModal only works after element's been inserted on the page

I'm using the jqModal plugin to attach a dialog box to a button click. I'm trying to attach the following box to the page:
suqBoxInner = document.createElement("div");
suqBoxInner.id = "suq_box_inner";
$(suqBoxInner).jqDrag('.jqDrag').jqResize('.jqResize').jqm({
trigger: '#suq_button',
overlay: 0,
onShow: function(h) {
return h.w.css('opacity', 0.92).slideDown();
},
onHide: function(h) {
return h.w.slideUp("slow", function() {
if (h.o) {
return h.o.remove();
}
});
}
});
However this only works if I run this binding code after the div's been inserted into the page. That is I have to use something like $("#div_on_page").after(suqBoxInner) before running the jqDrag code. What are my options for binding it before it's inserted into the page? I could use $.live() but that has to bind to a mouse event and the jqModal plug in uses bind on the trigger listed inside the function call.
It appears that this plugin requires the div (suqBoxInner) to be on the page. So short of modifying the plugin, I'm not sure you have many options as-is. Perhaps you may want to rethink how you are implementing the plugin? How is suqBoxInner being placed on the page? Is it after a specific event, or action?
One solution I can think of off the top of my head is to fire an event after suqBoxInner is placed on the page. The event would then initialize jqModal.
Just a thought. Good luck.

jquery tipsy plugin

Tipsy jquery plugin is installed in my app
This is in my load function
$(function() {
tipsy();
});
Below code is in a js file
var htm = '<div id="new_div" onmouseover="tipsy(this);">' ;
function tipsy(tip)
{
if ( '' != sumtitle )
{
tip.title = tip.innerHTML;
}
else if(tip)
{
tip.title = tip.innerHTML;
}
$(tip).tipsy({gravity: 'w'});
}
How is that the normal title shows up first and then the jquery tip later.
This is a known bug and will be fixed in the next version. For now please use the "Download Source" link on this commit:
http://github.com/jaz303/tipsy/commit/88923af6ee0e18ac252dfc3034661674b7670a97
The tipsy plugin seems to remove the title attribute and assign its value to a custom attribute called original-title to avoid the default browser tooltip from showing. Maybe in your case, this happens too late: The mouse hovers over the element, this initiates the native browser tooltip. Then, tipsy() is executed on the element and switches the attribute name, but that is too late because the timeout for the native tooltip has already started.
You should probably prevent the default action of the event, for example:
$('#new_div').bind('mousover', function (e) {
tipsy(this);
e.preventDefault();
});
EDIT: As this does not seem to have the desired effect, please call tipsy($('#new_div')) right after the div is created and remove the mouseover handler. What you have been doing might be a bit problematic anyway: The tipsy plugin probably uses the mouseover event, and you call .tipsy( { gravity: 'w' } ) in an onmouseover event handler. Repeatedly, if you mouseout and then mousover again. That's a lot of unnecessary event assignments.
You're doing it wrong.
Try this:
$('#new_div').tipsy();
jQuery is designed for using the selectors in JS code. No onsomething events in HTML, please.
Another way is, instead of using the 'title' attribute, use 'original-title' attribute.

Listen for change events in forms: JQuery

I have a form with an id of "wizard" - I only have select elements in this form. This form is in a lightbox using the JQuery plugin fancybox:
I want to know when any of these have been changed using JQuery. How can I do this? I currently have:
$('form#wizard select[name=servers], form#wizard select[name=cores]').change(function() {
var channels = parseInt($('form#wizard select[name=servers]').val(), 10) * parseInt($('form#wizard select[name=cores]').val(), 10);
$('#yellow').val(channels);
});
EDIT - I have the above wrapped in $(document).ready(function() {...}
However, it does not work, it does not even get run. I have put alerts in there and they never show up. The above only works when the above is a div that I have removed the display:none from, strange! So I am looking for a different implementation to get around this as I need that lightbox as it is.
I really need help on this.
Thanks all
The jQuery change function only binds those elements that are present when the domready event fires. If the lightbox plugin you are using is dynamically creating elements, you should be using jQuery's live function to "bind your handler to all current - and future matched elements".
Change this:
$('your selector').change(function() { /* code ... */ });
with this:
$('your selector').live('change', function() { /* code ... */ });

Categories

Resources