I am trying to add a css class to ajax loaded html element. My HTML look like as below:
<h4 class="overflow-text"><span>This is the response from the ajax call.</span></h4>
This h4 is a fixed width element and span inside h4 may be overflowing. So I need to add a CSS class for h4 if span text is overflowing. Here I am trying this with getting width of these two element and comparing it as below.
var el = $('h4.overflow-text');
el.each(function() {
var span = $(this).find('span')
if (span.width() > $(this).width()) {
$(this).addClass('text-marquee')
console.log('overflow')
} else {
console.log('not overflow')
}
})
This works for me, if html not load from ajax. But not working on ajax responce. So I tried it on ajax sussess as below. But it also doesn't work for me.
success: function(res) {
var $response = $("<div/>").html(res);
var wp = $response.find('.overflow-text').width();
var wc = $response.find('.overflow-text').children('span').width();
console.log(wp,wc)
$container.fadeOut( 50 , function() {
jQuery(this).html( res);
}).fadeIn( 1000 );
},
Doesn't works mean, wp and wc always giving 0.
Any help would be greatly appreciated.
Checking the width of the element after the content has been added to the DOM should work.
Edit: I saw that the DOM is not updated immediately however waiting for even a millisecond is enough and it gives the desired result.
$.get("spantext", function(data, status){
$('.container').fadeOut( 50 , function() {
jQuery(this).html(data);
$container = jQuery(this);
setTimeout(function(){
var wp = $container.find('.overflow-text').width();
var wc = $container.find('.overflow-text').children('span').width();
console.log(wp,wc)
},1);
}).fadeIn( 1000 );
});
Related
I use InnovaEditor to create edit block.
I try to find way in order to set dynamic height of edit block.
Ie block height should correspond block content.
HTML:
<iframe id="idContenteditor_field_1" name="idContenteditor_field_1" style="width:100%;height:100%;border:none;">
<html>
<head></head>
<body>12345</body>
</html>
</iframe>
What I did:
1) set keyup event in iframe body
2) wrap to content to get real height
3) set calculated height to the iframe
Javascript:
var $iframe = $("iframe#idContenteditor_field_1");
var $iframeBody = $iframe.contents().find("body");
$iframeBody.keyup(function(e) {
if ($(this).find('.content').length === 0) {
// add wrap
var bodyContent = $(this).html();
$(this).html('<div class="content">' + bodyContent + '</div>');
}
var $contentBlock = $(this).find('.content');
var bodyHeight = $contentBlock.outerHeight();
$('#idContenteditor_field_1').height(bodyHeight); // set real height
});
It works fine.
The issue:
I have 10 edit blocks on the page and they are same except id.
But I have problems when I try to apply this code to all iframes.
// return all iframes
var $iframes = $('iframe[id^="idContenteditor_field_"]');
// return only single body of first iframe.
var $iframesBody = $iframes .contents().find("body");
So I can't set keyup event for all iframes.
Could you help me?
Maybe there is easier way to set dynamic height?
var $iframesBody = $iframes .contents().find("body");
^^^ it returns only single body of first iframe, because rest iframes have not yet been loaded fully.
So I just execute this script after load of all iframes.
And it works.
I haven't tested this code, but something like below should work.
You just need to iterate through your objects and set the event listener for each one in turn.
var $iframes = $('iframe[id^="idContenteditor_field_"]');
$iframes.each(function(index, item) {
var $iframeBody = $(item).contents().find("body");
$iframeBody.keyup(function(e) {
if ($(this).find('.content').length === 0) {
// add wrap
var bodyContent = $(this).html();
$(this).html('<div class="content">' + bodyContent + '</div>');
}
var $contentBlock = $(this).find('.content');
var bodyHeight = $contentBlock.outerHeight();
$(item).height(bodyHeight); // set real height
});
});
I want to load all images before displaying them in a slideshow. I have been searching a lot but nothing seems to work. This is what i have so far and it doesn't work. I am loading images from the <a> tag from another div.
$('.slideshow').load(function(){
if (loaded<length){
first = $(settings.thumb).eq(loaded).find('a').attr("href");
$('<img src="'+first1+'"/>').appendTo('.slideshow');
}
else{ $('.slideshow').show(); }
loaded++;
});
Add an event listener to each image to respond to when the browser has finished loading the image, then append it to your slideshow.
var $images = $("#div_containing_images img");
var numImages = $images.length;
var numLoaded = 0;
var $slideshow = $(".slideshow");
$images.each(function() {
var $thisImg = $(this);
$thisImg.on("load", function() {
$thisImg.detach().appendTo($slideshow);
numLoaded++;
if (numLoaded == numImages) {
$slideshow.show();
}
});
});
It's a good idea to also listen for the error event as well, in case the image fails to load. That way you can increase numLoaded to account for broken image. Otherwise, your slideshow will never be shown in the event the image is broken.
Also note, that by calling detach() followed by appendTo() I am am moving the image in the DOM. If instead, you want to copy the image, use clone() instead of detach().
* EDIT TO MODIFY USER'S EXACT USE CASE *
var $images = $("li.one_photo a");
var numImages = $images.length;
var numLoaded = 0;
$images.each(function() {
$('<img />',
{ src: $(this).attr("href") })
.appendTo('.slideshow')
.on("load error", function() {
numLoaded++;
if(numLoaded == numImages) {
$('.slideshow').show();
}
});
});
* EDIT #2 *
Just realized you were putting everything in the $(".slideshow").load() function. Since $(".slideshow") represents a DIV, it will never raise a load event, and the corresponding function will never execute. Edited above accordingly.
What I'm trying to do is create a dynamic wall of images.
What I'm doing is this:
Call an API to get some response. Create an array of objects based on response
Based on the array, make HTML elements for each object where there's an img in it too.
When all of these HTML elements are created, attach it to the DOM, and call a final function.
This is what I have so far (truncated to get the point across):
EDIT: code has changed a bit. scroll to bottom of question for link to current code.
// based on one post, construct the html and return it
function getOneHtml(post, w) {
console.log("getting one html");
var outerDiv = $("<div>", {class: "brick"});
outerDiv.width(w);
var img = $("<img />");
img.attr("src", post.img_src);
img.on('load', function() {
console.log("img loaded");
var ratio = this.width / w;
h = this.height / ratio;
$(this).css({'height': h});
// ...
// ...
// create the element
// an alternative I'm using for now is directly append
// the created HTML onto the page, but that results
// in a kinda messy interface.
return outerDiv[0].outerHTML;
});
}
// queries an api and then calls callback after everything is done
function requestData(subreddit, callback) {
// array of objects with link to image, post title, link to reddit
posts = [];
var w = $(window).innerWidth() / 3,
html = ''; // holds all of the inner HTML for all elements
$.get("url here", function(data) {
var arr = data.data.children;
arr.forEach(function(res_post) {
console.log("looping in requestData");
// prepare a post object
// ...
// ...
html += getOneHtml(post, w); // get the HTML for this post
});
// this should happen after everything else is done
console.log("calling callback");
callback(html);
});
}
// complete the DOM
function makeWall(html) {
console.log("making wall");
// do stuff
}
Now the trace of the program in console is this:
looping in requestData
getting one html
looping in requestData
getting one html
... // bunch of times
calling callback
making wall
(20) img loaded
So now the problem is that the HTML isn't prepared until each image is loaded, and so it doesn't actually get attached to the DOM.
How can I make sure that things happen in order in which I want them to? I tried refactoring code into more of an async style but that didn't work (not my strongest point).
I also tried looking at $.Deferred but I don't understand it, and how to integrate it into my code.
Any help is appreciated.
EDIT:
I think it might help to see what I'm doing: http://karan.github.io/griddit/
When you load, I want the images to load first, and then fade in. Currently, they show up, then hide and then fade in. Here's the source: https://github.com/karan/griddit/blob/gh-pages/js/main.js.
Also, if you scroll down one or two pages, then scroll back up, some images show up behind others.
You can use .done(), as explained in the jQuery API documentation on .done() specifically explains how to use .done() with $.get().
It's as simple as:
$.get( "test.php" ).done(function() {
alert( "$.get succeeded" );
});
Concretely...
As the API documentation link provided above indicates, you can daisy chain .done() calls together.
$.get(url,handler).done(function(){console.log('calling callback')},callback);
Note, Not certain about functionality of included plugins, i.e.g., #grid layout,
css, etc. image width, height and #grid layout not addressed, save for existing pieces re-composed in attempt at flow clarity.
Piece below solely to fulfill // Do something when all dynamically created images have loaded requirement. See console at jsfiddle
Note also, piece at jsfiddle format issue. In order to test piece, drew in 2 plugins from links at original post. Tried jsfiddle's TidyUp feature, which inserted linebreaks.
Piece may need some re-formatting; though current jsfiddle does provide callback functionality, as per original post. Again, see console. Thanks for sharing.
updated
$(function() {
// the name of the last added post
var last_added = '';
// to control the flow of loading during scroll var scrollLoad = true;
var q = 'cats';
var callbacks = $.Callbacks();
// callback,
// Do something when all dynamically created images have loaded
var callback = function (cb) {
return console.log( cb||$.now() )
};
callbacks.add(callback);
function getOneHtml(post, w, count){
var img = $("<img>", {
"src" : post.img_src,
"width" : w
});
img.on('load', function(e) {
var ratio = e.target.width / w;
h = e.target.height / ratio;
$(e.target).css('height',h)
});
var link = $("<a>", {
"href" : post.permalink,
"target" : "_blank",
"html" : img
});
var outerDiv = $("<div>", {
"class" : "brick",
"style" : "width:" + w
});
$.when($(outerDiv).appendTo("#grid"),
$(link),
count)
.then(function(div, _link, _count) {
// `image` `fadeIn`; adjustable
$(_link).appendTo($(div)).hide(0).fadeIn(2000);
return _count
})
.always(function(_count){
callbacks.fireWith(window, [_count + " images appended to grid at " + $.now()])
});
};
function requestData(subreddit,callback) {
//array of objects with link to image, post title,link to reddit
posts=[];
var w = $(window).innerWidth() / 3;
html = '';
$.ajax({
type : 'get',
url : "http://api.reddit.com/r/" + subreddit + "/hot.json?&after=" + last_added,
beforeSend : function () {
$("#searchterm").addClass("loadinggif");
},
complete : function () {
$("#searchterm").removeClass("loadinggif");
},
success : function (data) {
var arr = data.data.children;
var count = null;
arr.forEach(function(res_post) {
if(!res_post.data.is_self&&(/\.(gif|jpg|jpeg|tiff|png)$/i).test(res_post.data.url)) {
// `images` count
++count;
var post = {
'title' : res_post.data.title,
'img_src': res_post.data.url,
'name' : res_post.data.name,
'permalink': 'http://reddit.com' + res_post.data.permalink
};
getOneHtml(post, w, count);
}
last_added = res_post.data.name;
});
scrollLoad = true;
// callback,
// Do something when all dynamically created images have loaded
// see `console`; adjustable
callbacks.fireWith( window, [$(".brick img").size() + " appended to grid, callback at " + $.now()]);
}});
}
// function makeWall() {}
})
jsfiddle http://jsfiddle.net/guest271314/ggsY9/
Is anyone able to determine, how to stop the jQuery caching the image that it grabs, and displaying the same image around and around again?
Basically the image is been re-uploaded every 5 seconds, as it acts as a webcam (if you check the time stamp on the bottom right of the image, you can tell if it's been updated or not)
http://colourednoise.co.uk/scripts/index.htm
Thank you
(sorry I forgot to hit paste for the code)
$(function(){
$(document).ready(function() {
var imgs = ['http://www.ramseycommunityradio.co.uk/images/webcam.jpg', 'http://www.ramseycommunityradio.co.uk/images/webcam.jpg']
$("#webcam").attr('src', imgs[1]);
var refreshId = setInterval(function() {
$("#webcam").fadeOut("slow", function() {
var $el = $(this);
$el.attr('src', $.inArray($el.attr('src'), imgs) === 0 ? imgs[1] : imgs[0]);
$el.fadeIn("slow");
});
}, 2000);
});
You could try appending a changing query string onto the URL, this should stop caching if that is indeed your problem. I've seen this done with a time stamp here: how to generate and append a random string using jquery
So each time you generate an image you do:
var qs = (new Date).getTime();
var url = 'http://www.example.com/images/myimage.jpg?' + qs;
$(el).attr('src',url);
your code:
var imgs = ['http://www.ramseycommunityradio.co.uk/images/webcam.jpg', 'http://www.ramseycommunityradio.co.uk/images/webcam.jpg']
$("#webcam").attr('src', imgs[1]);
var refreshId = setInterval(function() {
$("#webcam").fadeOut("slow", function() {
var $el = $(this);
$el.attr('src', $.inArray($el.attr('src'), imgs) === 0 ? imgs[1] : imgs[0]);
// this condition is redundant, it will ultimately give the same result always
// because imgs[0]==imgs[1]
$el.fadeIn("slow");
});
}, 2000);
as far a JQuery is concerned you are not changing the SRC attribute (JQuery knows nothing about the content of the image). Try using two different names in the server-side like webcam0.jpg and webcam1.jpg and alternating between them.
One trick is t append a random query string URL which causes the image to reload from the server. The code could be something like:
setInterval(function() {
var img = $("#img").get(0);
img.src = img.src.replace(/\?.*/, "") + "?" + Math.random();
}, 5000);
There may not be a fix for this. I am using a jquery drop down menu that loads when the DOM is ready. From what I understand this means it waits until the page is fully loaded until it becomes ready to be used.
This is problematic for a menu system because people want to use the menu right away often before the entire page is loaded.
Here is my site where you can see this happening.
http://bit.ly/g1sn5t
This is my script that I am using for the menu
$(document).ready(function() {
function megaHoverOver(){
$(this).find(".sub").stop().fadeTo('fast', 1).show();
//Calculate width of all ul's
(function($) {
jQuery.fn.calcSubWidth = function() {
rowWidth = 0;
//Calculate row
$(this).find("ul").each(function() {
rowWidth += $(this).width();
});
};
})(jQuery);
if ( $(this).find(".row").length > 0 ) { //If row exists...
var biggestRow = 0;
//Calculate each row
$(this).find(".row").each(function() {
$(this).calcSubWidth();
//Find biggest row
if(rowWidth > biggestRow) {
biggestRow = rowWidth;
}
});
//Set width
$(this).find(".sub").css({'width' :biggestRow});
$(this).find(".row:last").css({'margin':'0'});
} else { //If row does not exist...
$(this).calcSubWidth();
//Set Width
$(this).find(".sub").css({'width' : rowWidth});
}
}
function megaHoverOut(){
$(this).find(".sub").stop().fadeTo('fast', 0, function() {
$(this).hide();
});
}
var config = {
sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
interval: 0, // number = milliseconds for onMouseOver polling interval
over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
timeout: 0, // number = milliseconds delay before onMouseOut
out: megaHoverOut // function = onMouseOut callback (REQUIRED)
};
$("ul#topnav li .sub").css({'opacity':'0'});
$("ul#topnav li").hoverIntent(config);
});
function clearText(field){
if (field.defaultValue == field.value) field.value = '';
else if (field.value == '') field.value = field.defaultValue;
}
// JavaScript Document
Is there anyway to get this to load before everything else?
You can put those scripts wherever you whant in the case of understanding exactly what you are doing.
HTML are rendered sequentially, so scripts cannot get the DOM object or js variables defined later in the document. That's why we usually use document onload event to do the init thing since all elements are loaded.
In this case, I guess you can probably put the scripts without document.ready right after the closing of ul#topnav tag.