Can't drag dynamically added DIV - javascript

I have a DIV with id: TEST that I can drag using jQuery UI. All works, but as soon as I remove it and load the DIV into the HTML dynamically (well to specify more: using SSE to load the DIV into the HTML), the DIV can't be dragged. This is because the jQuery is loaded before the DIV is. How to fix this? Since I use SSE, the DIV is loaded several times over a period of time.
The jquery code:
$(function() {
$( "#TEST" ).draggable({
containment: "parent"
}).css({'cursor': 'all-scroll', 'z-index': '5'});
});
The DIV TEST is loaded into antoher DIV called dragZone
<div id="dragZone" name="dragZone"> [div TEST is loaded here] </div>
The JS that loads the SSE:
//HTML5 SSE(Server Sent Event) initilization
this.initSevr=function(){
sevr = new EventSource('test.php');
sevr.onmessage = function(e){
if(oldata!=e.data){
dragZone.innerHTML+=e.data;
oldata = e.data;
}
};
};
So how can I drag the DIV again? The Div is put into the HTML using SSE, this all works.

You will probably need to move your draggable code into the loading event, like this:
//HTML5 SSE(Server Sent Event) initilization
this.initSevr=function(){
sevr = new EventSource('test.php');
sevr.onmessage = function(e){
if(oldata!=e.data){
dragZone.innerHTML+=e.data;
oldata = e.data;
$( "#TEST" ).draggable({
containment: "parent"
}).css({'cursor': 'all-scroll', 'z-index': '5'});
}
};
};
This is assuming the DOM is updated immediately after innerHTML is used; if not it may be necessary to use a short setTimeout to make it draggable.

I think you forgot a quote, try to change from
sevr = new EventSource('test.php);
to
sevr = new EventSource('test.php');

Related

jQuery .append() with wait for render

I'm getting some html from a webservice that I'm appending to a div. This is my success function:
function SucceededCallback(result) {
// get the div element
var RsltElem = $(".placeholder");
// update div inner Html
RsltElem.append(result);
$('.loading-gif').hide();
}
Is there any way I can get .append() not to display until the browser is finished loading and painting it?
I'd rather not use .append(result).slideDown(n) as n could be anything, depending on what the webservice sends me.
Thanks in advance
Consider using
$( document ).ready(function() {
...
});
like so:
$( document ).ready(function() {
//get the div element
var RsltElem = $(".placeholder");
//update div inner Html
RsltElem.append(result);
$('.loading-gif').hide();
});
I don't know what you are painting and when it will complete, so you could also use this:
$(window).bind("load", function() {
// code goes here
});
Code inside the function only runs when the entire page has loaded.
$(window).on('load', function() {
//everything is loaded
});

variable in selector for click() not working

I have some buttons that should respond to a jQuery script. The buttons are to zoom and pan a svg image on a webpage. Because I want to have more than 1 svg files on a page a need my code to know which image I want to zoom. I can also use my mouse to zoom and pan (dragging), this works fine.
Short example
var currentID;
//get the id of the container around the image. This is: 'SVGfile' followed by a number
jQuery( ".svgcontainer" ).mousemove(function( event ) {
currentID = jQuery(this).attr('id');
});
var target1='#zoomInButtonSVGfile1';
var target2='#panRightButton'+currentID;
jQuery(target1).click(function(){ zoomIn(); }); //this works, but is hardcoded
jQuery("#zoomOutButtonSVGfile1").click(function(){ zoomOut(); }); //this works, but is hardcoded
jQuery(target2).click(function(){ panRight(); }); //this doesn't work
jQuery('#panLeftButton'+currentID).click(function(){ panLeft(); });//this doesn't work
In the first 2 opties I don't use the variable, but hardcode it, and then it works, but it doesn't serve my purpose.
The other 2 options should works as far as I know, and after searching for options. Somehow it does nothing... Can anybody spot my mistake?
If you are going to set a variable and then use it in order to bind an event, the event binding must also happen within the .mousemove.
jQuery( ".svgcontainer" ).mousemove(function( event ) {
if(!jQuery(this).data("bind")){
jQuery(this).data("bind", true);
var currentID = jQuery(this).attr('id');
var target1='#zoomInButtonSVGfile1';
var target2='#panRightButton'+currentID;
jQuery(target1).click(function(){ zoomIn(); });
jQuery("#zoomOutButtonSVGfile1").click(function(){ zoomOut(); });
jQuery(target2).click(function(){ panRight(); });
jQuery('#panLeftButton'+currentID).click(function(){ panLeft(); });
}
});

Adjusting height of scrolling div

I am combining two scripts together: a scroller and a content fader. When I swap the content (fading), div's with a lot of content make the scrolling div super long. I was reading on the plugin demo for content scrolling (http://manos.malihu.gr/jquery-custom-content-scroller) that you can use $(selector).mCustomScrollbar("update"); when loading different content to make the div adjust accordingly.
I know that code needs to go in my fading script somewhere, but where? Here is the fading script, where would it go?
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
(function($) {
$.fn.Fader = function() {
this.each(function() {
$('.clickme').bind('click', function(e) {
e.preventDefault();
$( "#mediaswap div" ).fadeOut();
$( "#mediaswap div" + $(this).attr('name') ).fadeIn();
})
});
}
})(jQuery);
$(function() {
$('#mediaswap').Fader();
});
});//]]>
</script>
I've answered your comment on the post but I'm writing it here too.
Since you fade in/out divs, you have to call the update method as a callback to the .fadeIn() function, so it updates the scrollbar after the animation is completed:
$( "#mediaswap div" + $(this).attr('name') ).fadeIn(function(){
$(this).mCustomScrollbar("update");
});
Additionally, there's an extra option parameter you can use when you initially call the plugin, that checks content size and updates the scrollbar automatically if it changes:
$("#mediaswap div").mCustomScrollbar({
advanced:{ updateOnContentResize:true }
});
Using the updateOnContentResize option, depends on the rest of your code (where you call the plugin), so I recommend using the first method.
I recommend checking the div to see if it's animated using something like this:
var wait = setInterval(function() {
if( !$("#mediaswap div").is(":animated"))
{
clearInterval(wait);
//put the code in here because it checks
for whether the DIV is currently animated.
}
}, 200);
You can change the interval if it takes the animation longer to complete the animation.

Transferring Onclick Function to jQuery

I have a jQuery function that replaces thumbnails with the main image.
This is the code that I use for replacing the main image:
$(document).ready(function(){
$(".wheelFinishThumbs a").click(function() {
var mainImage = $(this).attr("href");
var mainTemp = mainImage.replace(/-mid/,'');
var mainTemp = mainTemp.replace(/png/,'jpg');
$("#main_view img").attr('src', mainImage );
$("#main_view a").attr('href',mainTemp);
return false;
});
I use a PHP function to download (save) images by changing their header values. This is the HTML code that I use to download images
Click to download
but since "image.jpg" has to be my dynamic variable some how I've got to call this argument in the jQuery image replacement function and replace "image.jpg" dynamically each time I change the main image. I want to replace image.jpg with var mainImage from my image swapping function.
My jQuery knowledge is really limited, so If somebody can help me to do it, would be great.
This should work, assuming you are using jQuery 1.7+
Assuming your a tag markup is like this after you dynamically set the href to new image
Download Image
JavasScript
$(function(){
$(document).on("click","#main_view",function(e){
e.preventDefault();
var self=$(this);
alert("replace this with awesome code")
window.open('download.php?file='+self.attr("href")+,'_self', 'download', 'status=0');
});
});
Note that this function will work only of a single a element because we are targeting binding the functionality to the element with id main_view. Since ID's should be unique in the DOM, If you want to have the functionality to many a tags, i would add a common class selector to the a tag like this
<a class="aDownloadble" href="urltoSomeImage2.jpg" id="main_view">Download Image2</a>
<a class="aDownloadble" href="urltoSomeImage4.jpg" id="main_view">Download Image4</a>
And Update my script like this
$(function(){
$(document).on("click",".aDownloadble",function(e){
e.preventDefault();
var self=$(this);
alert("replace this with awesome code")
window.open('download.php?file='+self.attr("href"),'_self', 'download', 'status=0');
});
});
jQuery on is nnot necessary. you can simply use the click event binding directly. But if you are loading the markup of those links via ajax / injecting to the DOM dynamically, you should use on or live.
$(document).ready(){
$("#main_view a").click(function() {
// Code to run when user clicks on link
});
});

How do I run a jQuery function when any link (a) on my site is clicked

I have a new site build on corecommerce system which does not have much access to HTML and non to PHP. Only thing I can use is JavaScript. Their system is currently not great on page load speed so I wanted at least customers to know something is happening while they wait 5-8 seconds for a page to load. So I found some pieces of code and put them together to show an overlay loading GIF while page is loading. Currently it will run if you click anywhere on the page but I want it to run only when a link (a href) on the site is clicked (any link).
I know you can do a code that will run while page loading but this isn't good enough as it will execute too late (after few seconds)
Anyway, this is my website www.cosmeticsbynature.com and this is the code I use. Any help will be great.
<div id="loading"><img src="doen'tallowmetopostanimage" border=0></div>
<script type="text/javascript">
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
jQuery(document).click(function()
{
if(ns4){ld.visibility="show";}
else if (ns6||ie4)
var pb = document.getElementById("loading");
pb.innerHTML = '<img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0>';
ld.display="block";
});
</script>
Doing this will be easier if you include jQuery in your pages. Once that is done, you can do:
$('a').click(function() {
// .. your code here ..
return true; // return true so that the browser will navigate to the clicked a's href
}
//to select all links on a page in jQuery
jQuery('a')
//and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here)
jQuery('a').on('click', function () {
//my click code here
});
//and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched)
jQuery(document).on('click', 'a', function () {
//my click code here
});
Note: .on() is new in jQuery 1.7.
what you are doing is binding the click handler to the document so where ever the user will click the code will be executed, change this piece of code
jQuery(document).click(function()
to
jQuery("a").click(function()
$("a").click(function(){
//show the busy image
});
How about this - I assume #loading { display:none}
<div id="loading"><img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0></div>
<script type="text/javascript">
document.getElementById('loading').style.display='block'; // show the loading immediately
window.onload=function()
document.getElementById('loading').style.display='none'; // hide the loading when done
}
</script>
http://jsfiddle.net/vol7ron/wp7yU/
A problem that I see in most of the answers given is that people assume click events only come from <a> (anchor) tags. In my practice, I often add click events to span and li tags. The answers given do not take those into consideration.
The solution below sniffs for elements that contain both events, which are created with jQuery.click(function(){}) or <htmlelement onclick="" />.
$(document).ready(function(){
// create jQuery event (for test)
$('#jqueryevent').click(function(){alert('jqueryevent');});
// loop through all body elements
$('body *').each(function(){
// check for HTML created onclick
if(this.onclick && this.onclick.toString() != ''){
console.log($(this).text(), this.onclick.toString());
}
// jQuery set click events
if($(this).data('events')){
for (key in($(this).data('events')))
if (key == 'click')
console.log( $(this).text()
, $(this).data('events')[key][0].handler.toString());
}
});
});
Using the above, you might want to create an array and push elements found into the array (every place you see console.log

Categories

Resources