I'm trying to create a fadeout/fadein loop in plain/raw javascript however it seems like i can´t get the simpliest thing to work. The opacity filter itself. i have a div id="slideshow" and creating 2 dynamic childs. Img and div
<div id="slideshow">
//start dynamic part
<img src="image1.png" />
<div id="tooltip" />
//stop dynamic part
</div>
im creating these tags with javascript.
var slideshow = document.getElementById('slideshow');
slideshow.innerHTML ='<img src="image1.png" /><div id="tooltop"></div>':
im now trying to to give Slideshow´s child div opacity using javascript.
var slideshowDiv = document.getElementById("slideshow").getElementsByTagName("div");
slideshowDiv.style.opacity = 0.5;
slideshowDiv.style.filter = "alpha(opacity=50)";
is this not working becouse lack of eventhandler when new tags is created with javascript? else i dont understand the problem.
getElementByTagName returns a NodeList and not a HTMLElement.
Use index to retrieve a element from the NodeList.
For example, for the first element, you can do:
slideshowDiv[0].style.opacity = 0.5;
slideshowDiv[0].style.filter = "alpha(opacity=50)";
Index starts from 0 and the last index is (length of array - 1 )
Related
I have the following html.
<div class="new-row>
<img class="trash" src = "trash.png">
<img class="trash" src = "trash.png">
</div>
<div class="new-row>
<img class="trash" src = "trash.png">
<img class="trash" src = "trash.png">
</div>
Also I have the following jquery code
$(".trash").on("click",trashClicked);
How can I get the number of (".trash") in each new-row class. I don't want to get the total number of img tags with class trash. I want to get the specific number of img tags with class trash when a trash image is clicked in specific new -row
Inside trashClicked, this will refer to the specific img that was clicked. You can then work from there to figure out how many .trash imgs there are in that row:
Your img elements are siblings of one another, so you could use siblings:
var count = $(this).siblings().length + 1; // + 1 for the one we're calling it on
A more general solution would use closest to find the enclosing .new-row, and then find to find all of the .trash elements, even if they're at different levels.
var count = $(this).closest(".new-row").find(".trash).length;
It's well worth your time to read through the jQuery API, beginning to end. It doesn't take long, and it repays the time you spend doing it almost immediately.
How do I copy the content from all divs with a certain class or a certain beginning of an id to a bunch of divs with related id's? The examples I found didn't go through multiple copies. I have a solution that is working ok but instead of calling each copy with the id I would like to make the logic better.
Here's what I have now.
HTML (handlebars template)
<!-- the id comes from handlebar content. There are many like this -->
<pre><code id="target-example-01" class='language-markup'></code></pre>
<!-- this content is put to place once handlebars has rendered the page -->
<div id="code-examples" style="display: none;">
<div class='code-example' id="source-example-01">
this is my a code example... there are many like me...
</div>
</div>
Javascript
var source = document.getElementById('source-example-01').innerHTML;
var target = document.getElementById('target-example-01');
if (target) target.innerHTML=source;
This works ok but I have 100 examples so I wouldn't like to have 300 lines of code to manually maintain just to copy the content. How do I go through all the divs with "code-example" class and copy their content to divs with a matching id. All the source divs will have the id="source-(example-identifier)" and all the target divs will have the id="target-(example-identifier)". I guess the class wouldn't be needed if the code would go through all items with the id beginning with "source-"
I would be old school and stick with using getElementsByClassName() but since the question is how to target divs will have the id="target-(example-identifier) you can use querySelectorAll()
document.querySelectorAll('div[id^="source-example-"]')
for more information about querySelectorAll()
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
So the output is very much like using getElementsByClassName()
If you have any questions please leave a comment below and I will reply as soon as possible.
How to target a specific tag with a class and id?
document.querySelectorAll('div.code-example[id^="source-example-"]')
You will still need to loop through the contend just like you would for returning elements by class name but this query selector will only return div elements with the class name code-example and contains source-example- in the id attribute.
function QuerySelector() {
var Selector=document.querySelectorAll('div.code-example[id^="source-example-"]');
for(var i=0; i<Selector.length; i++){
alert(Selector[i].innerHTML);
}
}
<div class="code-example" id="source-example-01">Content Line One. - with class and id </div>
<div class="code-example">Content Line Two. - with correct class but no ID</div>
<div class="code-example" id="source-example-02">Content Line Three. - with class and id </div>
<button onclick="QuerySelector()">Get</button>
I hope this helps. Happy coding!
How do I go through all the divs with "code-example" class and copy
their content to divs with a matching id
Assuming that index of code-example elements is same as that of targets, then try
var allCodeExamples = document.getElementsByClassName( "code-example" );
for ( var counter = 0; counter < allCodeExamples.length ; counter++ )
{
var index = ("0" + counter).slice( -2 );
var target = document.getElementById( "target-example-" + index );
target.innerHTML = allCodeExamples[counter].innerHTML;
}
You can make use of data attributes for this using jquery:
<!-- the id comes from handlebar content. There are many like this -->
<pre><code id="target-example-01" class='language-markup'></code></pre>
<!-- this content is put to place once handlebars has rendered the page -->
<div id="code-examples" style="display: none;">
<div class='code-example' id="source-example-01" data-target="#target-example-01">
this is my a code example... there are many like me...
</div>
</div>
$(function(){
var targetId;
$(".code-example").each(function(){
targetId = $(this).attr("data-target");
$(targetId).html($(this).html());
});
});
I realised it makes more sense to check which examples are on the page and fetch the content for their source id's. I added another class to the code-tags "target-example"
Here's the javascript (jquery would probably make it nicer looking)
var examples = document.getElementsByClassName('target-example');
var i;
var id;
for (i = 0; i < examples.length; i++) {
id = examples[i].id;
var source = document.getElementById('source-'+id).innerHTML;
if (source) examples[i].innerHTML=source;
}
I've been going around in circles on this one. I have a PHP output that generates a series of DIV elements, and each has a class of L1, L2, L3, etc. These classes have a CSS that's basically blank so they display by default.
The problem is trying to change the class of each DIV to hide it, based on a simple onclick function. I'm using document.getElementsByClass to get (for example) just the DIV CLASS="L1" elements. But when I try to change the class, either with setAttribute('class', 'L1hide') or with className = "L1hide", nothing happens.
I know the HTML/CSS portion works, since I altered the PHP to generate "L1hide" instead of just "L1" and saw that the DIV CLASS="L1hide" elements were indeed hidden.
Is it because I'm trying to both grab the class and change the class at the same time? All the examples I see use getElementById, but this isn't practical for me since ID must be unique. I have zero, one, or more L1/L2/etc. class elements.
Here are some HTML code output by PHP:
<div class="L1"><h3>Owner</h3>
<table>
<tr><td>Jim Smith</td></tr>
</table>
</div>
<div class="L1"><h3>Executives</h3>
<table>
<tr><td>Harry Atkins</td></tr>
<tr><td>Galen Singh</td></tr>
</table>
</div>
<div class="L2"><h3>Managers</h3>
<table>
<tr><td>Andy Jones</td></tr>
<tr><td>Mary Thompson</td></tr>
<tr><td>Bill Murphy</td></tr>
</table>
</div>
And here is some javascript. This should change the image and hide the L1's. The image change DOES work (first 4 lines), but the style won't change (last 2 lines) despite my burnt offerings:
managmentImage.onclick = function() {
if (managmentLevel == "TOP1.png") {
document.getElementById("managementImage").setAttribute("src", "TOP0.png");
managmentLevel = "TOP0.png";
document.getElementsByClassName("L1").className = "L1hide";
divL1 = "L1hide";
} else { ...
Note: There is basically duplicate "else" code to change the image back, and to re-display the L1's. I only provided the first half of the "if" statement since the solution would also apply to the remaining "else" portion.
getElementsByClass is returning an array-like collection of nodes; those don't have className, individual nodes do.
You can't iterate it normally, because it is a live collection: if you change the class of the first element, the array shortens by one, so you will only process half of the nodes if you iterate from start to end. Iterating from end to start fixes this issue.
var elements = document.getElementsByClassName("L1");
console.log(elements);
var i = elements.length;
while (i--) {
elements[i].className = "L1hide";
}
.L1hide {
display: none;
}
<div class="L1"><h3>Owner</h3>
<table>
<tr><td>Jim Smith</td></tr>
</table>
</div>
<div class="L1"><h3>Executives</h3>
<table>
<tr><td>Harry Atkins</td></tr>
<tr><td>Galen Singh</td></tr>
</table>
</div>
<div class="L2"><h3>Managers</h3>
<table>
<tr><td>Andy Jones</td></tr>
<tr><td>Mary Thompson</td></tr>
<tr><td>Bill Murphy</td></tr>
</table>
</div>
getElementByClassName() returns an array.
You must iterate on it and then change the property.
I am using following code:
...
<div id="divcontainer1">
...
<div id="divcontainer2">
...
</div>
</div>
...
Now, I want change "divcontainer2" at a later point of time in the Div "divcontainer3".
What is the right way to check is exist divcontainer2 and when true,
change in divcontainer2 width javascript ?
Thank you,
Hardy
It is probably not nest practice but you can do this by changing the .outterHTML of the element. You would likely want to improve on this but here is a quick example. The last line checks if div 2 exists.
var div2 = document.getElementById("div2");
var html = div2.outerHTML;
var idx = html.indexOf(">");
var newtag = html.substring(0, idx).replace("div2", "div3");
div2.outerHTML = newtag + html.substring(idx, html.length - 1);
var contents = document.getElementById("div3").innerHTML;
alert(document.getElementById("div2") != undefined);
All you do is
get the element .outterHTML
get the substring representing the tag.
Replace the text that defines it
Set the .outterHTML tag to our new string
Now you have a newly named div that keeps all of its attributes, position in the parent and content.
The alert line is how you check for the existence of an object.
I don't believe that there is a "proper" way to do this, however I would store the contents of divcontainer2 in a variable, and then do something like this
var containerOfDivContainer2 = document.getElementById("containerofdiv2");
containerOfDivContaier2.innerHTML = "<div id='divcontainer3'>"/* insert div contents */+"</div>";
Of course, this requires you to put divcontainer2 in a div called containerofdiv2 but it works.
If using jQuery, this will do it:
$('#divcontainer2').attr('id','divcontainer3');
But you shouldn't be changing IDs. Use classes instead and then use the jQuery's toggleClass() function, like:
<div id="divcontainer1">
...
<div id="divcontainer2" class="style1">
...
</div>
$('#divcontainer2').toggleClass("style1 style2");
I got a (maybe a bit silly) question.
I'm making a photo gallery using javascript. I need to give every image some information (a id), so i can ask javascript what image is currently open.
Example:
I got a array of some images. Those images have a id 1, 2 and 3. When I'm using the gallery to slide through the images, I want to know what image Im looking at.
It can be done by giving the images alt the information I need. So I can go like;
var id = document.getElementById("image").alt;
But I though this wasn't the way to do it. Is there a simple solution for this problem?
I assume you have multiple <img> elements. You could give each of them the same class value so you can easily get a reference to all of them. You could then use data- attributes for any data you want to assign to them.
<img class="gallery-image" data-id="1" ...
<img class="gallery-image" data-id="2" ...
<img class="gallery-image" data-id="3" ...
JavaScript
var images = document.getElementsByClassName('gallery-image');
for (var i = 0; i < images.length; i++) {
var id = images[i].getAttribute('data-id');
...
}
You can add/remove a custom attribute using jquery to your image to indicate it's active:
$(..).attr('c-active', true);
will result:
<img src=".." c-active/>
Setting it to false will remove that attribute.
Since the attribute isn't a standard html syntax, some framework / browser might not be happy about it.
You can also use jquery data:
$(..).data('c-active',true);
$(..).data('c-active',false);
Or just keep a simple javascript variable to indicate which image id is active (but you will have to update this everytime the image slides)
var activeId = 5;