How to get a specific upper class of $(this) in jquery - javascript

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.

Related

Copy divs with certain id's to targets with related id's

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

Giving information to a image

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;

Remove filepaths from multiple image elements in HTML using jQuery

I'm trying to keep the filenames but remove the filepaths from the image elements on my page, and I've managed to figure out the following based on what I've already gathered from similar questions.
I'm able to remove just the filepaths, but I can't figure out why the source of the first image is being copied into the other two images.
Here's what I've put together so far
HTML
<img src="/path/to/image.gif" />
<img src="/different/path/to/picture.jpg" />
<img src="another/path/to/graphic.png" />
JS
var abc = $('img').attr('src');
var def = abc.split('/').pop();
$('img').attr('src', def);
RESULT
<img src="image.gif">
<img src="image.gif">
<img src="image.gif">
http://jsfiddle.net/aztdeu0w/
You arent iterating through all the img elements, try the following:
$('img').each(function(){
var imgName = $(this).attr('src').split('/').pop();
$(this).attr('src', imgName);
});
That way you will loop through all the images and replace accordingly the src attribute.
This is how jQuery works. The $ selector grabs an array of items (containing 0-N matched elements) and then applies your operations to those elements. For some operations though- read operations like attr('src') it only makes sense to read a single item, so it reads the first one.
What you want is to iterative over the images and apply your regex to them one at a time. So...
$('img').each(function(index, item){
// Read/write attr here
});

set opacity to child div with javascript

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 )

How can accomplish a dual div swap on rollover?

I am looking for advice on a way to accomplish this. Given the following:
[Div A (contains an image)]
[Div B (contains a horizontal list of 8 or so text links)]
[Div C (contains text)]
Upon rolling over any link in Div B, how can I have Div A and Div C swap their respective contents out to something different that corresponds to the content of that link?
For example, if one were to rollover a Div B link called "Dogs", then upon that rollover, Div A would replace its contents and display an image of a dog and Div C would replace its contents and display text about dogs.
After rolling over that link, the new Div A and Div C contents will remain in place until a new link is rolled over.
I hope this makes sense. Does anyone have advice on the best way to accomplish this?
Assuming the href points to one resource that contains the content for both, but you can't just inject the entire output of the link into one element, something like this could work:
$('#divB a').mouseover(function() {
//get images from link, inject into divA
$('#divA').html('<strong>Loading...</strong>')
.load($(this).attr('href') + ' img');
//get divs from link, inject into divC
$('#divC').html('<strong>Loading...</strong>')
.load($(this).attr('href') + ' div');
});
Hmm... this should be pretty simple with jQuery (compared to some of the other answers here):
If you're unfamiliar with jQuery, the $() is a shortcut for calling jQuery(), and using
$(document).ready(function() {
// put all your jQuery goodness in here.
});
is a way to make sure jQuery fires at the right time. Read more about that here.
So first, add a class (ie .dogs) to each <a> element in your #divB list. Next, give each of the corresponding images the same class, and contain each of your text blocks in #divC in divs with the same class as well. The HTML would look something like this:
<div id="divA">
<img src="dogs.jpg" class="dogs" />
<img src="flowers.jpg" class="flowers" />
<img src="cars.jpg" class="cars" />
</div>
<div id="divB">
<ul>
<li>Dogs</li>
<li>Flowers</li>
<li>Cars</li>
</ul
</div>
<div id="divC">
<div class="dogs"><p>Text about dogs.</p></div>
<div class="flowers"><p>Text about flowers.</p></div>
<div class="cars"><p>Text about cars.</p></div>
</div>
Then use the following jQuery, putting this up in the <head> section of your HTML doc:
$(document).ready(function() {
$('a.dogs').hover(function() {
$('#divA img').hide("fast");
$('#divA img.dogs').show("fast");
$('#divC div').hide("fast");
$('div.dogs').show("fast");
});
});
We say when the document is ready, when you hover over the <a> element with the .dogs class, perform a function. That function will hide all of the images in #divA and immediately show the image with the .dogs class. Then it will hide all of the divs in the #divC and immediately show the div with the .dogs class.
You can do the same thing twice more for .flowers and .cars, or however many you have.
Keep in mind, there are more efficient ways of doing this too, if you're interested in looking deeper into jQuery, but this will be a solid way to get started in helping you understand exactly what jQuery is doing. And it keeps the script OUT of the HTML body, too!
You can change a div's contents with something like this:
<script type="text/javascript">
function over() {
var a = document.getElementById('a');
var c = document.getElementById('c');
a.style.backgroundImage = "url(/path/to/image)";
c.innerHTML = "<b>Dogs rock</b>";
}
</script>
<div id="a"></div>
<div id="b" onmouseover="over();"></div>
<div id="c"></div>
Then all you need to do is add whatever other div's you want and write code to change them appropriately. Set the initial state of A and C using css, or just call the over() function on page load.

Categories

Resources