Mootools new Element does not work - javascript

new Element does not work. Someone has any clue why?
css:
#tileNode {
position:absolute;
width:100px;
height:100px;
background-color:red;
}
js:
window.addEvent('domready', function() {
var newElement = new Element('div',{id:"tileNode"});
newElement.inject($$('div#tileNode'));
alert($$('#tileNode').get('id'));
});
Alerting #root works fine so it exists... creating that tileNode element does not work alerting it also does not work :/
Kind regards!

use
newElement.inject($('root'));
If you inject in the div with the id 'root',also you have to inject in a single element, use $('id') because the $$ returns an array…

There are few things in your code that took my attention:
Fist is, new Element('div',{id:"tileNode"}) is completely equal to new Element('div[id=tileNode]'). Since it makes no difference what way you choose, I'd recommend the second form, because it is a lot more readable. You could even add more attributes like Element('div[id=tileNode][class=tile]') and so on, instead of passing an object.
Another optimization would be to use the dollar function if you are trying to get an element by its id. So if you want to alert the id of an element, try to use alert($('tileNode').id).
Though alerting might work fine, you could try to use the javascript console. Instead of alert(myVar) use console.log(myVar).
Hope this helps, and happy coding :)

you can also use this to inject:
newElement.inject($$('div#tileNode')[0]);

Related

Add html in jquery with differents contents

I have this little script for add differents parts of code to the body in website
WincontentBody=jQuery("<div class='wd_"+idw+"'id='win_container'>OK</div>");
WincontentBody=jQuery("</div>");
jQuery(WincontentBody).fadeIn(3000).appendTo('body');
I try to add code from WincontentBody to body but it doesn't work, some kind of error i have in syntax, because never show div
I think this it's fine but I can't find the problem, the idea it's to add all contents from the variable WincontentBody to the body
Is it possible to do this? Because i can't make it to work
Thank´s in advanced
I went ahead and wrote your question properly for you. Take a look at SO in Spanish.
fadeIn and appendTo are jQuery methods. WincontentBody contains a string. You should first create a new jQuery object with your html.
$(WincontentBody).appendTo('body').fadeIn(3000); //first append, then fade in
If the fadeIn doesn't seem to work, it's probably because you will have to hide the elements (with some css) before inserting them into the page. Otherwise you'll be trying to fade in something that's already visible.
And I don't know if your code is actually formatted like that or it just got wrapped here, but you can't have multiline strings, unless you end each line with \.
Now (after your edit), you are creating two jQuery objects. One with the div and the other with nothing valid.
WincontentBody=jQuery("<div class='wd_"+idw+"'id='win_container'>OK</div>");
//WincontentBody now has the div
WincontentBody=jQuery("</div>");
//WincontentBody now has nothing. The </div> is not being appended to what was in WincontentBody before, you're assigning a new value to it
jQuery(WincontentBody).fadeIn(3000).appendTo('body');
//You're appending WincontentBody (which has nothing valid) to the body
//Also, WincontentBody is already a jQuery instance, no need to call jQuery() again
What you should do is to create your WincontentBody with the html code, as you had before, and then use $(WincontentBody)... or jQuery(WincontentBody).... Or put the whole html code in a single jQuery element like:
var WincontentBody=jQuery("----all the html code at once----");
WincontentBody.appendTo("body").fadeIn(3000);
Try this.
$(document).ready(function() {
WincontentBody = "<div class='wd_asdfas'id='win_container'>OK This is fine.</div>";
$('.displayHere').append(WincontentBody);
$('.displayHere').fadeIn(3000);
});
body { background: #eee }
.displayHere { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>
<div class="displayHere">
Hello Buddy
</div>
</body>
Updated
I had made few changes.
I add the div named displayHere. I don't think it is good idea to
give the fade effect to body of the webpage.
In jquery I split the functions to two different functions. Firstly it will update the details and then it will fade in.

How to change InnerHtml to an attribute

Can some one show how I can change the InnerHTML of the titles class to be the same as the alt attribute. For the actual website jarretonions.co.za
Thanks
$(document).ready(function() {
$(".pic").on("click", function() {
$(".modal").show();
var srclong = $(this).attr("src");
var srcshort = srclong.split("_");
var srcextension= srclong.split(".");
$(".modal img").attr("src", srcshort[0]+'.'+srcextension[1]);
************is it something like this********
var title = $(this).attr("alt");
$(".modal span").InnerHTML= title;
OR
document.getElementByClassName('titles').innerHTML = title;
})
+
echo
"<div class='art'>
<img class='pic' src='img/".$row["name"]."_tnail.jpg'
alt='".$row["name"]." • ".$row["year"]." • ".$row["type"]."'
height='auto' width='100%'/>
<div class='modal'>
<img class='big'/>
<span class='titles'></span>
</div>
</div>"
;
Since you're using JQuery, you can select those elements using $(".title") and change them directly. Something like so:
$(document).ready(function() {
$(".pic").on("click", function() {
$(".title").text( $(this).attr("alt") );
})});
Here's a fiddle: https://jsfiddle.net/wmjtfLja/1/
Note that if you have more than one element of class .title, they will all change. So you may want to select the title element by id or by relative path from the clicked image.
Realizing in advance, the danger of providing an answer that is not (superficially) fully aligned with the question, I was struck by the comment from melpomene, whom I initially thought was refering to things not existing in jquery.
melpomene is 100% correct, since getElementByClassName does not exist.
The correct syntax is getElementsByClassName.
Having said that, helloworld is also correct (syntax errors aside), since loading jquery for every little task is really redundent, and one can manipulate by class with little more half a dozen lines of pure javascript.
But, getting elements by class has dangers, since the return is a 'live' array.
For example, with dylan's original question, getting by class is only useful to return the first instance (the array length is just a guide of how many elemnts it applies to). Therefore, for dylan to make changes as he proposed, each requires its own button. (which also means, michael that I believe you are incorrect when you say it will affect all elements with same class name - oth, you are fully correct in noting that one should inpsect for other values (or change the class name) when running loops on the attribute).
Consider the following (on the fly class change);
function otf_cls_change(cls_original,cls_replace){
var a=document.getElementsByClassName(cls_original);
l=a.length;
if (l==0){return 0;}
do {
a[0].setAttribute('class',cls_replace);
a=document.getElementsByClassName(cls_original);
l=a.length;
} while (l>0);
}
This is effective for changing class names on the fly.
But, if we modify the code and
//change this a[0].setAttribute('class',cls_replace); // to
a[0].innerHTML='this_html';
It will cause the browser to hit an endless loop.
Why? because the live array returned by ElementByClass will only process the first item (even if you try to loop the array).
Therefore, while changing the class on the fly is fun and very do-able, I'd strongly suggest that using it to change any attrib that is not specific to the class id is a bad idea.
Changing the class attrib in conjunction with another attrib is fine.
For example,
a[0].innerHTML='this_html'; //do this first
a[0].setAttribute('class',cls_replace); //then this
The above will work to loop class defined elements.
On a point of massive personal hypocrisy, I do get annoyed when people ask for pure javascript solutions, and then some wing nut chimes in with jquery. I guess I'm doing the opposite here, since evidently, the question was jquery related, and here I am throwing out pure javascript. Sorry bout that.
btw, dylan, good luck with it. glad you bit back on the negative comment. Too many people here are terrified of offending, and wind up get bullied.
hth,
Gary

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);
};

Cant get an attribute of an element with jquery

I have got this html:
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">
I am trying to get this:
$('body').on('click','.hostPic',function(){
console.log($(this).attr('data-name'));
});
Whenever the picture is pressed, I want to gets its data-name attribute, but it doesnt work.. I get undefined reported when I try to retrieve the attribute. Any reason why?
Add the hostPic class to that image.
Additionally, you can just use .data('name'), but it doesn't actually make a difference. Older browser may have trouble with .data, but it's never been a problem for me.
$('.hostPic').click(function() {
console.log($(this).data('name'));
}
Make sure your image has the class 'hostPic' and then do the following in your jQuery:-
$('.hostPic').on('click', function() {
console.log($(this).data('name'));
}
The following code worked for me, maybe you are attaching the events wrong object, you can understand that by debugging the this object instead of data-name.
And another thing is if you are going to use .data just for read string you should use .attr as the .data caches and tries to convert the value its appropriate type like number or JSON it is a heavier process than .attr.
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">​
​$("img")​.click(function () { alert($(this).attr("data-name")); });​

JQuery .attr won't retrieve or change values

I'm trying to change HTML attributes using jQuery, but no matter what I do, I can't get anything to work with jQuery's .attr().
For testing, I've written
alert($("#logo").attr("title"));
and even though I have an img with id="logo" and a title, the alert remains blank.
My full method:
function switchVideo(videoID) {
var videoPlayer = document.getElementById("example_video_1");
videoPlayer.src = "video/Occam.webm";
videoPlayer.load();
$("#example_video_1").attr("poster", "video/ss.png");
//Doesn't work:
alert($("#logo").attr("title"));
$("#logo").fadeOut();
videoPlayer.play();
}
My fade out works, so I know I imported jQuery correctly.
I've gotten it working in another document, so there must be something else in the document messing it up. Does anyone know why this simple method won't work?
You can see the source page at http://jrstrauss.net/temp/create.html
Your div has the id logo, not the img.
Try:
$("#logo img").attr("title")
You should be using $.fn.prop for that now: http://api.jquery.com/prop/
You should use prop if you are using a recent version of jQuery.
You can also try this according to your HTML:
alert( $("#logo a img").attr("title") );
Demo
You have the following markup with id logo
<div id="logo">
......
</div>
Now, you are trying to run jQuery's .attr method by following code.
$("#logo").attr("title");
as you may know .attr method retrieves attribute value of the given element but that <div> doesn't have a attribute named title. so to confirm this, try retrieving attribute that does exist, for example id. so try this
alert($("#logo").attr("id"));
This will return the value of attribute. the important thing to note is jQuery looks for attributes of given element only, It doesn't scan child elements.
So, to make it work in your case. You need to do the following
alert($("#logo img").attr("title"));
Hope it helps

Categories