When i click on a element with a class named sections, i should get an alert showing what is it's class index, but it's showing a wrong number.
For example, if i click the first div element with a class named sections, javascript alert should say 1, not 3.
Is there a way to target class indexes with click() using jQuery?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>this is the title</title>
<style>
.sections {
width:200px;
padding:30px;
background:blue;
margin:20px;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div class="sections"></div>
<div class="sections"></div>
<div class="sections"></div>
<script src="jquery-1.8.2.min.js"></script>
<script src="script/script2.js"></script>
<script>
$('.sections').click(function() {
x = $(this).index();
alert(x);
});
</script>
</body>
</html>
index() with no arguments gets index within all siblings.
You have 6 siblings....3 with the class and 3 without
Try
var $sections = $('.sections').click(function(){
var x = $sections.index(this);
alert(x);
});
You need to pass in the selector against which you want to index of ( if you want to get the index based on the specific class )
x = $('.sections').index(this);
$('.sections').click(function() {
x = $('.sections').index(this);
alert(x);
});
.sections {
width: 200px;
padding: 30px;
background: blue;
margin: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div class="sections"></div>
<div class="sections"></div>
<div class="sections"></div>
You are correct index(), is used to find index of an element with respect to its siblings but correct way to use it in your code is.
$('.sections').click(function() {
var x = $('.sections').index(this);
alert(x);
});
Also, please note that it will start from 0 instead of 1.
https://api.jquery.com/index/
So, as you noticed, it's alerting it's index for itself among it's siblings in the DOM. (starting at 0)
If you want to get it's index among similar objects, you can use .index slightly differently.
$('.sections').click(function(){
x = $('.sections').index($(this));
alert(x);
});
This is still 0 based, so you can now expect that it will show 0 for the first item, then 1 and 2.
From the documentation:
If we omit the argument, .index() will return the position of the first element within the set of matched elements in relation to its siblings:
Your first .sections element is in 4th position among its siblings, so it returns 3 (the first being 0).
You want to pass a selector or an element to index().
Related
i need help getting this to work, tried everything google had to offer.. but still stuck. what i need it to do is load the value of (div id="availablecredits") to (div id="beta") on click. can any body help me out?
onclick="javascript:document.getElementById('beta').value=(javascript:document.getElementById('availablecredits').value)"
i also tried onclick="javascript:document.getElementById('beta').value=('#availablecredits')"
The property value is common for input elements like <input>, <select>, <textarea> and <button>
I think what you want is to copy a content of a <div> element to another div. If it's the case, use innerHTML instead of value.
Here is a snippet, just click on the gray area.
#div-two {
min-height: 20px;
background: #CCC;
}
<div id="div-one">
Hello this is #div-one
</div>
<div id="div-two" onclick="document.getElementById('div-two').innerHTML=document.getElementById('div-one').innerHTML"></div>
SNIPPET #2
You've defined a third <div> which you use as trigger but you can't click it if it's not visible, because it's height is 0. Specify some text inside it, then it's visible and the JS part work. Take a look at the snippet.
#getCredits {
background: #CCC;
}
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits" onclick="document.getElementById('beta').innerHTML=document.getElementById('availablecredits').innerHTML">Click here to get available credits</div>
SNIPPET #3 - jQuery
$('#getCredits').click(function() {
$("#beta").html($('#availablecredits').html());
});;
#getCredits {
background: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits">Click here to get available credits</div>
Simple javascript function, change the ids in the function call to those of the elements in question.
<script>
function set_value( src,tgt ){
document.getElementById( tgt ).innerHTML=document.getElementById( src ).innerHTML;
}
</script>
<style>.p5{ display:block; padding:1rem; margin:1rem; border:1px solid black;}</style>
<div class='p5' id='src_div' onclick="set_value('src_div','tgt_div')">Weebles wobble but they don't fall down!</div>
<div class='p5' id='tgt_div'></div>
Or you can use a link to set the value
you should try to avoid writing inline event.try this:
<style>
#getCredits {
background: #CCC;
}
</style>
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits">Click here to get available credits</div>
<script>
document.getElementById('getCredits').addEventListener("click",function(){
document.getElementById('beta').innerHTML=document.getElementById('availablecredits').innerHTML;
});
</script>
Why inline css and javascript are bad:http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/
The .val() method is sometimes useful:
var input = $("#Input").val();
I have this code:
<div id="parent">
<div>
<div id="Container1" >
<div id="Container1">
<object>.....</object>
</div>
</div>
</div>
<div onclick="appear()" id="child-2">
<div id="child-of-child"></div>
</div>
</div>
I've put the CSS bellow to stop display the first child of div#parent and I'm trying to display with a reaction via JavaScript.
CSS
div#parent div:first-child div:first-child {
display: none;
}
How can I display the the second div#Container1 also?
Because if I use the code bellow, it displays only the first div#Container1.
Javascript
<script type="text/javascript">
function appear() {
document.getElementById("Container1").document.display="block";
}
</script>
Thanks in advance.
If you have access to CSS change it to:
div#parent > div:first-child > div:first-child {
display:none
}
:first-child does not specify its immediate first child, you can use > to specify that and avoid second Container1 from using that style rule.
With this change you can use your existing javascript. and remove id from the child div at a later time without affecting this.
http://jsfiddle.net/oz5g3bxs/
And of course, use unique id as already mentioned by everyone
If you can't change the IDs (and I suggest you try), you can use. This is only relevant if both divs were not set to display block beforehand.
function appear() {
var containers = [];
var parent = document.getElementById("Container1");
containers.push(parent);
containers.push(parent.children[0]);
for (var i = 0; i < containers.length; i++) {
containers[i].style.display = "block";
}
}
http://jsfiddle.net/wxsgpeuk/2/
Note this is purely to get it done in your situation as Joe mentioned in the comments: duplicate IDs is just doing it wrong.
This is my whole code..what I am trying to do is to have-. when DOM is ready first div shows on page and second one after a delay and then third one and so on up to 150.
Problem with the current code is that, whole 150 div loads at once after a small delay.
My code -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test for dashed div</title>
<style type="text/css">
.dashdiv
{
width: 150px;
height: 50px;
background: #ae2d3e;
float:left;
box-shadow: 10px 10px 6px #d4a7b0;
margin: 5px;
}
</style>
</head>
<body>
<?php
for($i =0; $i < 150; $i++)
{
?>
<div class="dashdiv">
This is a div text
</div>
<?php
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('div.dashdiv').each(function()
{
$(this).hide().delay(1000).fadeIn(1850);
});
});
</script>
</body>
</html>
The problem you're facing, which no one has mentioned, is that jQuery delay() is only chainable on an fx queue. So, using it after hide() will not work. A quick fix to get it working would be to use an effect in place of hide(), ie:
$('div.dashdiv').each(function(i) {
$(this).fadeOut(0).delay(1000*i).fadeIn(1850);
});
Try using the index argument that is automatically assigned for every iteration of each to extend the delay in a linear manner:
$('div.dashdiv').each(function(i) {
$(this).delay(1000*i).fadeIn(1850);
});
Also, following your comment, the style of the div elements should be changed to make them hidden:
.dashdiv {
display:none;
...
}
You can use :
Html:
<div id="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
jQuery:
$('#parent .child')
.hide()
.each(function(index){
var _this = this;
setTimeout( function(){ $(_this).fadeIn(); }, 5000*index );
});
demo at http://jsfiddle.net/gaby/eGWx9/1/
Here's a way to delay and fadeIn a div only once the previous div has finished.
It uses the fadeIn callback to move to the next div in the array:
// hide all
$('.dashdiv').hide();
// fade in each div one by one
divs = document.getElementsByClassName('dashdiv');
(function fade(i){
if(i < divs.length){
$(divs[i]).delay(1000).fadeIn(1850, function(){
fade(++i);
});
}
})(0);
Or without getElementsByClassName.
// hide all
$('.dashdiv').hide();
// fade in each div one by one
(function fade(i){
if(i < $('.dashdiv').length){
$($('.dashdiv')[i]).delay(1000).fadeIn(1850, function(){
fade(++i);
});
}
})(0);
Demo: http://jsfiddle.net/louisbros/RdxS6/
I have annotated text, and I'd like certain annotated words to be color-coded along with their annotations, but I don't want to have to do it manually. Is there a way to have javascript (or jquery) or even css make the first class="Noted" green, then the second blue, and then on the fifth go back to green, and to do the same with the corresponding class="note"s?
you can do this using :nth-child you will need something like jQuery for support for IE though.. working on that...
here's a first fiddle for a CSS only version http:http://jsfiddle.net/zhQ67/2/ ** FIDDLE updated with new code below **
CSS:
.noted:nth-child(4n+1) {
background: green;
}
.noted:nth-child(4n+2) {
background: red;
}
.noted:nth-child(4n+3) {
background: yellow;
}
.noted:nth-child(4n+4) {
background: blue;
}
final update using thirtdots updated code and including some jQuery for IE - JSBIN Page
Ok, based on your jsFiddle you could use something along these lines to get the result you're after:
p:nth-child(5n+1) .Noted, p:nth-child(5n+1) .Annotation {color: green}
as demonstarted in this modification of your jsfiddle
You can get all elements with getElementsByClass an then simply iterate through them, giving every single one and it's corresponding element class="note" a different color.
In jquery.....set the colors as you see fit. jsFiddle demo
<script type="text/javascript">
$(".Noted").each(function(i,e){
switch(i%4){
case 0: $(this).css({color:"#f00"});break;
case 1: $(this).css({color:"#0f0"});break;
case 2: $(this).css({color:"#00f"});break;
case 3: $(this).css({color:"#ff9"});break;
case 4: $(this).css({color:"#f90"});break;
}
});
</script>
First, try encapsulating your elements inside a container. It will make the children selection much easier.
<div id="parent">
<span class="note">Green</span>, <span class="note">blue</span>
then <span class="note">red</span>.
</div>
then, the js :
<script>
var children = document.getElementById('parent').getElementsByTagName('*')
,colours = ['green','blue','red','orange']
,i,j=0,max;
for (i = 0, max = children.length; i<max; i++) {
if(children[i].getAttribute('class') == 'note') {
children[i].setAttribute('style','color:' + colours[j]);
j++;
if (j>colours.length) {
j = 0;
}
}
}
</script>
If the HTML is being generated by a server side script, you could have the script assign a class based on which Annotation is being generated, then in the stylesheet, assign a color to that class, like so:
.note1 { //Corresponds to class='note1'
color: green; //or whatever you want
}
.note2 { //Corresponds to class='note2'
color: blue; //or whatever you want
}
/* and so on */
If the HTML is simply being written statically, then assign the class corresponding to how it defined in the stylesheet, depending on the color you want.
If they are children, you could use something along the lines of clairesuzy's solution.
The other option is to assign all of them as class note and then have an javascript that colors everything marked as class note based on a predefined order that you set.
That would probably be along the lines of something like this (using jQuery):
Demo here: http://jsfiddle.net/hs8Nm/
<p class="note">Note 1</p>
<p class="note">Note 2</p>
<p class="note">Note 3</p>
<p class="note">Note 4</p>
and the corresponding Javascript:
$(document).ready(function(){
var colors = ['green','blue','orange','yellow',"FFFFF0"]; //Assign your color order here.
$('.note').each(function(index){
this.css('color',colors[index%5]);
});
});
Yes, it can be done using CSS Selectors. You can get the first, second, third, and so on element in a list of matching occurences.
Here you go:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<title>Cycle classes</title>
<style>
.blue {
background-color: blue;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
</style>
<script>
$(document).ready( function() {
$(".Noted").each(function(i) {
var classes = ['green','blue','yellow'];
$(this).addClass(classes[i % classes.length])
});
})
</script>
</head>
<body>
<div class="Noted">hello</div>
<div class="Noted">world</div>
<div class="Noted">it works</div>
</body>
</html>
The following code allows the user to click on the question of a flashcard and it displays the answer.
The problem is it displays all the answers for all the flashcards.
How can I pass the id of each flashcard so that the user can click on the title and toggle the question open and closed?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript"
src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.4.0");
google.setOnLoadCallback(function() {
$("div > div.answer").hide();
$("div > div.question").click(function() {
$("div > div.answer").fadeIn("slow");
});
});
</script>
<style>
div.flashcard {
margin: 0 10px 10px 0;
}
div.flashcard div.question {
background-color:#ddd;
width: 400px;
padding: 5px;
}
div.flashcard div.answer {
background-color:#eee;
width: 400px;
padding: 5px;
}
</style>
</head>
<body>
<div id="1" class="flashcard">
<div class="question">Who was Wagner?</div>
<div class="answer">German composer, conductor, theatre director and essayist, primarily known for his operas (or "music dramas", as they were later called). Unlike most other opera composers, Wagner wrote both the music and libretto for every one of his works.</div>
</div>
<div id="2" class="flashcard">
<div class="question">Who was Thalberg?</div>
<div class="answer">a composer and one of the most distinguished virtuoso pianists of the 19th century.</div>
</div>
</body>
</html>
You don't need to pass in the ID. Just traverse from the div clicked to the answer you want. this refers to the source of the event, which will in this case be a div with class "question".
$("div.question").click(function() {
$(this).next().fadeIn("slow");
});
Also, assuming your markup is accurate this can be simplified:
$("div > div.answer").hide();
to simply
$("div.answer").hide();
but I would actually do it with CSS:
div.answer { display: none; }
so no Javascript needs to be executed when the page loads. In my experience when using an async load of jQuery with the Google AJAX Libraries API like you are, the page will render and then your flashcard answers will visibly disappear. This tends to be undesirable. Just use CSS to hide them.
Also, jQuery is as of a day or two ago up to version 1.4.1.
Since the two divs are siblings, you can use the next method to get the next div.answer element:
$("div > div.question").click(function() {
$(this).next("div.answer").fadeIn("slow");
});
Check an example here.
When you are inside the event, you need to reference the this keyword, so that you are in the proper context. Otherwise, you are selecting globally, rather than specifically.
google.load("jquery", "1.4.0");
google.setOnLoadCallback(function() {
$("div.flashcard div.answer").hide();
$("div.flashcard div.question").click(function() {
$(this).next('div.answer').fadeIn("slow");
});
});
This should be code you are looking for. I tested and it is working.
<script type="text/javascript">
google.load("jquery", "1.4.0");
google.setOnLoadCallback(function() {
$("div > div.answer").hide();
$("div > div.question").click(function() {
if($(this).siblings('.answer').css('display') == 'none')
$(this).siblings('.answer').fadeIn("slow");
else
$(this).siblings('.answer').fadeOut("slow");
});
});
</script>