error in converting js code to jQueryMobile - javascript

I have a javascript/jquery code http://jsfiddle.net/9773D/ for timer.
I am trying to port it to jQuery Mobile code but I am confused about the pageinit,bind,live etc window events.
In the code i see that the error is because some elements in the tick() function are not loaded in DOM before it has been invoked in the code. Can someone help me in correcting my code.
Thanks,

I changed your line to
var timeDisplay = $(".time")[0];
and that fixes it.
Edit:
Adding explanation:
Since you used innerHTML instead of $('.time').html(""), you needed to set timeDisplay to the HTML node, since innerHTML is a property of the node, not the jQuery object that is returned by the selector $('.time').

Here's a jsfiddle that shows how it could be done in a more jquery'sh way. http://jsfiddle.net/9773D/1/
timedisplay.innerHtml = "" //does not work since timedisplay is a jquery object
//timedisplay[0] is the html object so on that innerHtml does work
But jquery has the function .html("");
timedisplay.html(""); // is a bit cleaner

Related

Jquery, cannot access css properties of dynamically generated element

I am using jQuery to append elements to a div, and all works fine.
var new_div = $('<div>My stuff</div>');
new_div.appendTo("#container");
However, I'd like the div to appear by fading in, instead of abruptly.
I notice though that I get an error when I try to access graphic properties on my dynamically generated element. So this, for example fails:
new_div.hide().fadeIn();
The console reports the following error:
TypeError: jQuery.curCSS is not a function
Do I understand this correctly, that this fails because current css properties are not defined for the dynamically generated element? Or what else can be goingg wrong?
Important edit
Additional checking and working on this pointed out to a complete misunderstanding from my part. This has nothing to do with the fact that the element was dynamically generated. I got the same thing by calling fadeIn() on whatever element.
I sincerely apologize!
I still didn't get, though, why this happens
Adding elements to the DOM takes some time, miliseconds maybe, but it's still a reason for jquery not be able to find the element.
This process might be even slower if the DOM is a large html page.
Write your code like this:
var new_div = $('<div>My stuff</div>');
new_div.appendTo("#container");
setTimeout( function(){
new_div.hide().fadeIn();
} , 150); // 100 could be also good
It might be enough time for jquery to catch the element.
I would add an id to keep track of all elements I'm creating (just my preference, but it makes it easier to code it).
var new_div = '<div id="myNewDiv1" style="display:none;">My Styff</div>'
$('body').append(new_div);
$('#myNewDiv1').fadeIn();
It does seem to be a compatibility question, although I wasn't able to figure out exactly why and how to fix it.
Adding this code fixes the problem though:
jQuery.curCSS = function(element, prop, val) {
return jQuery(element).css(prop, val);
};

document.getElementById('id') problems

folks,
I have on my pages (http://playdota.thilisar.cz) a JavaScript file(code below), that has to have an effect of modyfying the edge of the icons(for real, it has to load new picture) and loading the information(only plain text so far) into a div with ID "info" on mouseover event;on mouseout event it has to load the original picture to same position. But it only writes informations and replaces icons with "[object Object]" text.
I hope, you understand this, because my english isn't very good.
Thanks for your answers.
function showInfo(id){ //Using jQuery 1.7.2
document.getElementById('ses').innerHTML=$(function(){
$.ajax({
url: "sentinel_str/"+id+"-info.html"
}).done(function(data){
$("#info").html(data)
})
$("#ses").find("li").mouseover(function(){
$id=$(this).find("img").attr("id")
$(self.document[$id].src='look/icons/'+$id+'_hover.jpg')
})
$("#ses").find("li").mouseout(function(){
$id=$(this).find("img").attr("id")
$(self.document[$id].src='look/icons/'+$id+'.jpg')
})
})};
CLOSED THANKS TO CHEESEWARLOCK'S ANSWER
Thanks all, who tried to help me.
You are setting the innerHTML of the element to the value of the return of the jquery object. In effect you're saying put the 'toString' value of this function as the content of the HTML.
Do you mean to have? Unless I'm reading it wrong.
document.getElementById('ses').innerHTML=$(function(){
You're getting [object Object] because you're setting the contents of an HTML element to a jQuery object. If you want to call a piece of jQuery code, you don't need to wrap it in $(). You can just call the code directly. So get rid of this line:
document.getElementById('ses').innerHTML=$(function(){
and this line:
})
and the rest of your code will be executed when you call showInfo(id).
The "mouseover" and "mouseout" handlers look pretty confused to me. There's no need to call getElementById() at all; you're using jQuery, and you can find the <img> tags with it. Once you've found them, you've found them; no need to find them again.
$("#ses").find("li").mouseover(function(){
$(this).find('img').prop('src', function() {
return 'look/icons/' + this.id + '_hover.jpg';
});
})
$("#ses").find("li").mouseout(function(){
$(this).find('img').prop('src', function() {
return 'look/icons/' + this.id + '.jpg';
});
})
Passing a function as the second argument of .prop lets you compute the value of the property using the DOM element state directly.
Also you might want to use "mouseenter" and "mouseleave", which are sanitized by jQuery and are a little more reliable than "mouseover" and "mouseout".
edit — wow I just "zoomed out" and noticed that all this code is being set up as an innerHTML value, which makes no sense. Looks like a case of rampant copy/paste or something.
The code written below would solve your problem and is even short. Check it out once.
var id;
$('#ses').find('li').each(function(){
$(this).mouseover(function(){
var image=$(this).find('img');
id=$(this).find('img').attr('id');
$('#id').hide();
$(this).append('<div>'+id+'</div>');
});
$(this).mouseout(function(){
$(this).html('');
$('#id').show();
});
});

using javascript to output html

I have a javascript link that references another .js file. I've been trying to output an image (for testing purposes), but I'm not sure what is the correct way to go about this.
alert("beginning");
//var link = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
//$('body').append(link);
//document.write("hi");
//document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("before function");
(function(){
alert("middle");
var links = $("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
$('body').append(links);
alert("after middle");
//alert($("img").attr("id"));
document.write("hi");
document.write("<div><img src='http://s3-media2.ak.yelpcdn.com/bphoto/xqC6Iy5mOLb_8mwMKGv8_w/l.jpg' /></div>");
alert("end");
}());
I was able to alert beginning, all the way to middle. It seems like var links doesn't work. I'm trying to use HTML inside this .js file. Essentially, I want to be able to do some modal window, but I'm trying to output images for testing purposes right now.
Also, is this the correct way for jquery?
Thanks in advance!
Your code is a strange mix. Jquery code almost always needs to run after the page has loaded whereas document.write can never be used after the page has loaded.
You are incorrectly wrapping your jQuery in an immediate executing function. The proper wrap for jQuery is within :
$(document).ready(function(){
/* html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
or the shorthand version that does same thing:
$(function(){
/*html of page exists now, run jQuery here */
});// notice no extra "()" after close brace as you have
If you change all of your document.write to $('body').append(/* your content*/) and place all your code inside the above wrappers you will have much better success.
There is a wealth of information within the jQuery documentation and API. A good start point with more detail about the wrapping I've shown can be found here: http://docs.jquery.com/How_jQuery_Works
Your biggest problem is addressed in the other answer. You are improperly wrapping JQUery so essentially JQuery is not ready to be executed when it reaches your append statement.
It is unnecessary to wrap your html in a JQuery object (in this case):
var links = "<a href='http://juixe.com'>Hello, <b>World</b>!</a>";
$('body').append(links);
or simply:
$('body').append("<a href='http://juixe.com'>Hello, <b>World</b>!</a>");
In terms of best practice, using append, appendTo or prepend are good options depending on the context. You could also use:
$("body").html("/*Your HTML here*/")
At the end of the day you have many options but avoid document.write at all cost. The non-JQuery approach would be to use .innerHTML with a DOM element. This is also a good approach in the absence of JQuery.

Unexpected result of document.getElementById.value?

When I run the following code:
document.getElementById('somevar').value = '25';
alert(document.getElementById('somevar').value );
"somevar" is displayed, instead of 25. Why is this? Thanks in advance for any help.
EDIT: input type of 'somevar'is hidden
I suspect this is happening because when you run the code the element you're trying to access is not yet ready. Make sure you run your code after the DOM has loaded by using onload for plain javascript or the ready event if using jQuery.
As show on my fiddle, if an element is defined with the right name, it show the correct result:
http://jsfiddle.net/Achilleterzo/kcp2n/
It should work.
Here is a sample on JsFiddle

jQuery objects don't work

When I store a jQuery object in a variable, like this:
var $myObject = $("div#comments");
...I can't use the object $myObject!
This is what I'm doing to change the html of div#comments:
$myObject.html(data);
It does nothing. I already tried this way too, this time to select an element inside div#comments:
$("div.comment", $myObject);
It doesn't work.
I just want to be able to save an element in a variable and then use it!
Note: some people don't put $ before the variable name, like this: myObject.
Are you calling it after the document is loaded?
// This will ensure that the code doesn't run until
// the document has loaded
$(function() {
var $myObject = $("div#comments");
});
(This is a shortcut for jQuery's .ready() method.)
http://api.jquery.com/ready/
As long as the document is loaded, and you have a <div> with the ID comments on the page when it loads, it should work.
Also remember that there can only be one element on the page with any given ID. Because of this, it is actually a little better (quicker) to do $("#comments"); instead of $("div#comments");.
You've only provided snippits of your code, so it is impossible to tell for sure, but the odds are that you are running the code in a <script> element that appears before the <div> element and don't do anything (such as use the ready event) to delay the execution of the code until the div exists.
The result is that you get a jQuery object which found no elements. Move the script element so it is after the div. Just before the end tag for the body is a good place.
The syntax is perfectly valid and should work. Are you dynamically appending the comments div? You should alert( $myObject.length ) to see if it's 0 or 1, if its 0 that means it's never picked up.
You may need to bind the var statement until after dom ready, window load, or your ajax callback.
Well, that syntax is perfectly fine so something else is going on. Can you show your markup? And what do you get if you add an alert($myObject.length)? And one last thing to check... are you running this inside an on-ready handler?
Ok, thanks everyone for that.
I got the solution.
I thought about the order the things were loaded in the DOM and found the solution.
The problem (with the markup) was:
<div id="comments">
<script type="text/javascript">
loadComments(params);
</script>
</div>
The code above was written by PHP!
So it executed the function as soon as the browser read the code.
I already tried to put the script on the end of the page, after the function was called. The funcion was not defined yet.
So, the funcion loadComments should be executed after the div was ready AND after the function was defined.
I wrapped the code between the tags with a .ready(), like this:
<script type="text/javascript">
$(function() {
loadComments(params);
});
</script>
It was a distraction.
Sorry everyone!
Thanks a lot.
If you have the same problem and you didn't understand what I did, ask me. XD

Categories