I have a few sets of javascript codes and divs just below them:
<script type='text/javascript'>
jQuery(document).ready(function(){
jQuery(".display").something({
/*myfunction*/
});
});
</script>
<div class="display"></div>
<script type='text/javascript'>
jQuery(document).ready(function(){
jQuery(".display").something({
/*myfunction*/
});
});
</script>
<div class="display"></div>
(...)
Is there a way of selecting only the .display div after exact JS? I've been thinking about next() but it's hard to attach to document.ready ;)
You should give each <div> an id and attach handlers that way.
Javascript doesn't really care where within HTML you write it. Put all your Javascript in a script file and refer to DOM elements by className/id.
Just give each DIV a unique id, and use that id in your selector.
You could give the script tag a unique id and call next():
<script id="script-tag-1">
jQuery(function() {
var node = $('#script-tag-1').next('.display');
});
</script>
<div><!-- content --></div>
jsFiddle: http://jsfiddle.net/SYgEX/
Everything was generated dynamically (that's why I asked how to change my JS code, WITHOUT touching DOM!).
Anyways I've found the best way.
<?php $id = rand(); ?>
<script type='text/javascript'>
jQuery(document).ready(function(){
jQuery(".display-"<?php echo $id;?>").something({
/*myfunction*/
});
});
</script>
<div class="display-<?php echo $id;?>"></div>
Not perfect, but it works at least (and could possibly break, but chances are really low).
Related
Hello guys I want to dynamically append the div to the div that i click. Here is the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="query.js">
$('.hello').click(function(){
$(this).append('<div>I am the new one</div>');
});
</script>
</head>
<body>
<div class="hello1">Hello guys</div>
<div class="hello2">Hiiiiiiii</div>
<div class="hello3">Awesome</div>
</body>
</html>
Can anyone tell me whats the issue with my code
There are 3 problems in your code
You can't have src and contents for an script tag
Since your script is placed before the elements are loaded, you need to put your script in a dom ready handler
There is no class called hello in your html
so
<div class="hello">Hello guys</div>
<div class="hello">Hiiiiiiii</div>
<div class="hello">Awesome</div>
<script src="query.js"></script>
<script>
jQuery(function ($) {
$('.hello').click(function () {
$(this).append('<div>I am the new one</div>');
});
})
</script>
Try wrap your jquery code in document.ready like
$(document).ready(function(){ // this will execute when DOM is ready
//your code
$('.hello1').click(function(){ //updated class name
$(this).append('<div>I am the new one</div>');
});
})
As i can see you are using hello class to bind click event your it
doesn't present in your HTML. So if you want to attach event to all
class start with hello use this:
$(document).ready(function(){
$('div[class^="hello"]').click(function(){
$(this).append('<div>I am the new one</div>');
});
});
DEMO
Instead of this
<script src="query.js"> //don't use src here
Use:
<script type="text/javascript">
Try this : You don't have div with class="hello" but class which starts with hello viz hello1, hello2, hello3. Hence use start with selector as shown below. Also put your code inside $(document).ready(function... or $(function(){... so that it will ensure DOM is ready and will attach click event handler.
You must include jquery library first and then put jquery script in another script tag.
<script src="query.js"></script>
<script>
$(function(){
$('div[class^="hello"]').click(function(){
$(this).append('<div>I am the new one</div>');
});
});
</script>
You need to include jQuery before and for using it. Use
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
You cannot load script and define script inside it. So, following is not valid
<script src="query.js">$('.hello')...</script>
Use ready() or DOMContentLoaded event or move the script to the bottom of <body>
There is no element with hello class in the markup, but you're binding the event on it.
Code:
<script src="query.js"></script>
<script>
$(document).ready(function() {
$('.hello').click(function() {
$(this).append('<div>I am the new one</div>');
});
});
</script>
Demo
$(document).ready(function() {
$('.hello').click(function() {
$(this).append('<div>I am the new one</div>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="hello">Hello guys</div>
<div class="hello">Hiiiiiiii</div>
<div class="hello">Awesome</div>
First of all, in order to use $() selectors you need to include a proper version of jquery. Then, you need to select an element: you have any element with hello class, instead, you have hello1, hello2, and hello3. You could remove the numbers, so all of them will have a hello class. And finally, because these elements doesn't exist when the js code is executed, you need to wrap your code within a document ready event, or move it to the end of your html body tag. Good luck!
There is no .hello class in your code, you use hello1, hello2 and hello3 as classnames, they should all just be hello.
I encounter a very strange problem!
I wrote the following code:
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<textarea id="code">
<div id="hello">Hello world!</div>
<script type="text/javascript">
$(function(){
$("#hello").css({"border":"solid 3px red"});
alert($("#hello").size());
});
</script>
</textarea>
<iframe src="iframe.html"></iframe>
<script type="text/javascript">
$(function(){
$("iframe").on("load",function(){
$(this).contents().find("body").append($("#code").val());
});
});
</script>
The "iframe.html" file contains only a call to the jQuery library.
The result is that "Hello world!" is displayed in the iframe but without red border! It seems that $("#hello") does not work. In fact, if I do alert($("#hello").size()), I get "0".
Do you have any idea?
Thanks!
Edit: Add "alert".
$(this).contents().find("body").append($("#code").val());
Only gets the current value so probably it wont copy over any css value that is linked to it.
http://api.jquery.com/val/
What I suggest is testing it in 1 file first to see what it does so remove the iframe part for now and check the .size() on 1 file. that way you know how the .val and .size() behave on your #hello.
Try this as the script under the :
<script type="text/javascript">
$(function(){
$("iframe").on("load",function(){
alert($("#code").val());
var scriptx = $("#code").val();
$(this).contents().find("body")[0].innerHTML = scriptx;
});
});
</script>
});
</script>
I think the html format is wrong. You are putting the div inside the text area and inside any text area if you put some html elements then those are simply taken as some text and that html elements are not going to render in browser.
So you can put the the div element out side the text area.
<textarea id="code"></textarea>
<div id="hello">Hello world!</div>
I hope this will work.. :)
How to add a class to first div using jQuery.
I Tried following code but doesn't work for me.
maybe I'm missing something.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script>
$('.item')
.eq(0).addClass('first').end()
.eq(-1).addClass('last').end();
</script>
<style type="text/css">
.first, .last{
background-color:#0099FF;
}
</style>
</head>
<body>
<div class="item">aaa</div>
<div class="item">bbb</div>
<div class="item">ccc</div>
<div class="item">ddd</div>
<div class="item">eee</div>
</body>
</html>
Edit: Thanks to everyone, is there anyway to add a class to rest of DIVs?
You are executing the code before the markup is ready. Wrap the code in
// document ready short-style
$(function() {
});
try
$(document).ready(function() {
$('.item:first-child').addClass('first');
});
Your code is correct, but it's executed before the DOM is ready, please move the <script></script> to the last line before </body>.
To add a class to the rest of the elements you can do this (from VisioN's comment)
$(".item:not(:first,:last)").addClass("differentClass");
$(".item :first").addClass('first');
u use this code
$(function(){
$(".item:first-child").addClass("anyclass");
})
or
$("div:first-child").addClass("anyclass");
your code should execute when the DOM is fully loaded. So use $(document).ready().
the script can be run as soon as the DOM hierarchy has been fully
constructed. The handler passed to .ready() is guaranteed to be
executed after the DOM is ready, so this is usually the best place to
attach all other event handlers and run other jQuery code.
Read more about $(document).ready().
check the code below. It will help you to get done what you want.
$(document).ready(function() {
$('.item').first().addClass('first');
});
Otherwise your js is ran even before the DOM is loaded
$(".item:first").addClass('first'); will work fine too.
Try the demo too.
Hope this will help you out. If you have any questions please don't hesitate to ask. Thanks
Here is the jQuery code
<script>
$(document).ready(function(){
$('body .item:first').addClass('YOUR CLASS VALUE');
});
<script>
Regards,
http://www.santoshkori.com
see jsfiddle here
$(document).ready(function() {
$('div:first').addClass('first');
});
You could always use straight CSS, although it is CSS3. E.g. you could replace your curre t CSS with:
.item:nth-of-type(1), .item:nth-of-type(3)
{
background-color:#0099FF;
}
If you do just want jQuery then you could try:
$('.item:first').addClass('first');
$('.item:last').addClass('last');
Try this
JS CODE
$(document).ready(function(){
$('div.item')
.eq(0).addClass('first').end()
.eq(-1).addClass('last').end();
});
DEMO
Note
you need to use $(function() { ... }) to wrap whole jQuery code.
I have jQuery on my webpage.
I am changing background color of a div.
Its not working.
<script type="text/javascript">
$("#gridbox").css({'background-color':'black'});
</script>
Your code should work, try using document ready handler.
$(document).ready(function(){
$("#gridbox").css({'background-color':'black'});
})
http://jsfiddle.net/WcQse/
Its possible your script is running before the DOM has loaded. Try:
<script type="text/javascript">
$(document).ready(function(){
$("#gridbox").css({'background-color':'black'});
});
</script>
-- Demo --
Try this
If you are using ASP.NET then your Client ID might change depending on the use of Master Pages in that case you can try something like this.
$('#<%= gridbox.ClientID %>' ).css('background-color','black');
If it is just a div then you should wrap it in document.ready() method
$(document).ready(function(){
$('#gridbox').css('background-color','black');
});
Demo
The same code that you are using is working fine for me
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="gridbox" style="background-color:red;">gridbox</div>
<script type="text/javascript">
$("#gridbox").css({'background-color':'black'});
</script>
</body>
</html>
so you should first include the jquery library, then put the javascript file after the div that you want to change the background color.
Try:
$("#gridbox").css("background-color", "black");
Edit:
Add a document ready function, this will execute the css change after the DOM has loaded.
$(document).ready(function() {
$("#gridbox").css("background-color", "black");
});
Note: Ensure you have the jQuery JavaScript file referenced in the page.
I'm trying to write a javascript function that adds some DOM nodes to the document in the place it was called, like this:
...
<div>
<script type="text/javascript">
pushStuffToDOMHere(args);
</script>
</div>
...
i try to do it 'cleanly', without using node id property of the div, or innerHTML string manipulation. for that I need to know where in the document the script tag is located.
is there a way to do it?
Talking about cleanly, I don't think your approach is particularly clean. It is a much better idea to give the div a unique id and execute your javascript when the DocumentReady-event fires.
Do you have an overriding reason for doing it this way? If not the suggestion to use a unique id makes the most sense. And you can always use a library like jQuery to make this even easier for yourself.
However, the following quick test shows that if you use document.write() in the function then it writes the value into the place where the function was called from.
<html>
<head>
<script type="text/javascript">
function dosomething(arg){
document.write(arg);
}
</script>
</head>
<body>
<div>The first Div</div>
<div>The
<script type="text/javascript">
dosomething("Second");
</script>
Div
</div>
<div>The
<script type="text/javascript">
dosomething("Third");
</script>
Div
</div>
</body>
</html>
But, again the question, are you sure this is what you want to do?
Although I agree with n3rd and voted him up, I understand what you are saying that you have a specific challenge where you cannot add an id to the html divisions, unless by script.
So this would be my suggestion for inlining a script aware of its place in the DOM hierarchy, in that case:
Add an id to your script tag. (Yes, script tags can have ids, too.)
ex. <script id="specialagent" type="text/javascript">
Add one line to your inline script function that gets the script element by id.
ex. this.script = document.getElementById('specialagent');
...And another that gets the script element's parentNode.
ex. var targetEl = this.script.parentNode;
Consider restructuring your function to a self-executioning function, if you can.
Ideally it executes immediately, without the necessity for an 'onload' call.
see summary example, next.
SUMMARY EXAMPLE:
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode.nodeName=="DIV" && this.script.parentNode;
//...your node manipulation here...
}('arg1','arg2','arg3');
</script>
The following TEST code, when run, proves that the function has identified its place in the DOM, and, importantly, its parentNode. The test has division nodes with an id, only for the purpose of the test. They are not necessary for the function to identify them, other than for testing.
TEST CODE:
<html>
<head>
<title>Test In place node creation with JS</title>
</head>
<body>
<div id="one">
<h2>Child of one</h2>
<div id="two">
<h2>Child of two</h2>
<script id="specialagent" type="text/javascript">
var callMe = function(arg1,arg2,arg3) {
this.script = document.getElementById('specialagent');
var targetEl = this.script.parentNode;
/*BEGIN TEST*/
alert('this.script.id: ' + this.script.id);
alert('targetEl.nodeName: ' + targetEl.nodeName + '\ntargetEl.id: '+targetEl.id);
alert('targetEl.childNodes.length: ' + targetEl.childNodes.length);
var i = 0;
while (i < targetEl.childNodes.length) {
alert('targetEl.childNodes.'+i+'.nodeName = ' + targetEl.childNodes[i].nodeName);
++i;
}
/*END TEST - delete when done*/
//...rest of your code here...to manipulate nodes
}('arg1','arg2','etc');
</script>
</div>
</div>
</body>
</html>
Not really sure what your trying to achieve but this would pass the dom element to the function when clicked. You could then use jquery in the function to do what you wanted like so
...
<script type="text/javascript">
function pushStuffToDOMHere(element)
{
$(element).append("<p>Hello</p>"); // or whatever
}
</script>
<div onclick="pushStuffToDOMHere(this);">
</div>
...
my solution is a compbination of the (good) answers posted here:
as the function is called, it will document.write a div with a unique id.
then on document.onload that div's parent node can be easily located and appended new children.
I chose this approach because some unique restrictions: I'm not allowed to touch the HTML code other than adding script elements. really, ask my boss...
another approach that later came to mind:
function whereMI(node){
return (node.nodeName=='SCRIPT')? node : whereMI(node.lastChild);
}
var scriptNode = whereMI(document);
although, this should fail when things like fireBug append themselves as the last element in the HTML node before document is done loading.