How to add a unique id to first of kind - javascript

ok. Building out a employee directory. At the top of the directory is the alphabet so you can click on a letter an arrive at the first person who has that letter as first letter of last name. How can i loop through the all of the employees and add an id of the letter to the first of each. I haven't built out the markup, yet, but for now it could be as simple as
<h3><span class="fname">Johnny</span><span class="lname">Willis</span></h3>
</div> ```
Where I would target the last name and add an ID to the card
I am pulling all of the content in from a hubspot hubdb. Unsure if that is relevant, but wanted to add that.

I think you don't need to add an ID to each of the last names from your list. If you just want to scroll down to the first item when clicking the alphabet index, try this:
HTML
<!-- A container for the alphabet letters -->
<div id="alphabet">
<span id="letter-a">A</span>
<span id="letter-b">B</span>
<span id="letter-c">C</span>
<span id="letter-d">D</span>
</div>
<!-- A container for each last name -->
<div id="employee-a" style="height:500px">
<p>A</p>
<p>Adams Mike</p>
<p>Addison John</p>
<p>Adkins Smith</p>
</div>
<div id="employee-b" style="height:500px">
<p>B</p>
<p>Bain Chris</p>
<p>Barker Travis</p>
<p>Banner Brock</p>
</div>
<div id="employee-c" style="height:500px">
<p>C</p>
<p>Carl Steve</p>
<p>Carter Aaron</p>
<p>Castle Vania</p>
</div>
<div id="employee-d" style="height:500px">
<p>D</p>
<p>Daenerys Targaryen</p>
<p>Dale Denton</p>
<p>Daniels Jack</p>
</div>
JAVASCRIPT
<script>
// Wait until DOM is fully loaded
$(document).ready(function() {
// Get the ID name from the letter you clicked
$('#alphabet > span').on('click', function() {
// Pass this ID name to a variable
var letter = $(this).attr('id');
var goTo = letter.split('-').pop();
// Use it to smooth scroll to the position of the first last name with the letter you clicked
$('html, body').animate({
scrollTop : $('#employee-' + goTo).offset().top
}, 500);
})
});
</script>
Hope this helps.
Enjoy!

Related

Show multiple divs

so, I'm working on a project that has 2 tables in database that are related!
I need via JavaScript Hide and Show the divs containing the right information.
I got a main product Stone, and each Stone has 2 other Stone Types
So if I click on the img that has Stone1, I want to show Stone1.1, Stone1.2, etc and hide all the other StoneTypes.
This is what I got now on JS
jQuery('.Pedras').click(function(){
jQuery('.SubPedras').hide();
jQuery('#div'+$(this).attr('target')).show();
});
The problem here is that I only get the first div to show, eventhough I have 2 divs with the same Name example:
<div id="div{IdPedra}" class="SubPedras">
<div id="div{IdPedra}" class="SubPedras">
<div id="div{IdPedra}" class="SubPedras">
And {IdPedra} Is the id of the stone in the database, so I will get "div1" two or 3 times, etc.
Can anyone pls help me, I'm not able to find a suitable solution for my need.
Thank you!
You could use data-attributes to accomplish this. In your change my code to;
<div data-id="{IdPedra}" class="SubPedras">Stone 1.1</div>
<div data-id="{IdPedra}" class="SubPedras">Stone 1.2</div>
<div data-id="{IdPedra}" class="SubPedras">Stone 2.1</div>
<div data-id="{IdPedra}" class="SubPedras">Stone 2.2</div>
You can access an element's data-attribute by using $(element).data("name"); this is equivalent to data-name. I also stored the Pedras
Loop through the SubPedras and check if they match the button where the parent category or value you wish to use as filter. Run the snippet, thanks!
(You could also store them to class attribute instead of data)
jQuery('.Pedras').click(function() {
// store button value to variable
var pedraValue = $(this).val();
// loop through the SubPedras
$(".SubPedras").each(function() {
// get the value from data attribute
if ($(this).data("id") == pedraValue) {
// if match show
$(this).show();
}
else{
// else hide
$(this).hide();
}
});
});
.SubPedras{
line-height:40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-id="Stone1" class="SubPedras">Stone 1.1</div>
<div data-id="Stone1" class="SubPedras">Stone 1.2</div>
<div data-id="Stone2" class="SubPedras">Stone 2.1</div>
<div data-id="Stone2" class="SubPedras">Stone 2.2</div>
<button class="Pedras" value="Stone1">Stone 1</button>
<button class="Pedras" value="Stone2">Stone 2</button>

targeting only same page anchor links

From a web analyst perspective on any given website i am looking find out which same page anchors are clicked the most by console logging the anchor's text value (inner html text) in the console for now.
The approach i took was to take the current page url after every anchor click and check to see if their had been any hash changes at the end of the url string and if so print that anchor's text value in the console.
var anchor = $("a[href^=\\#]");
anchor.on("click", function(){
if("onhashchange" in window) {
var anchorText = this.text;
console.log(anchorText);
}
});
I'm having issues with the code I wrote because its returning the inner Html text for any anchors on the page(except the ones with external links) but I only want to track the ones that lead to a section on the same page.
Would the approach i took need to be revised to even begin with ?
Here is some of the html I am working with and different anchors I want to track and ones I don't.
<!-- Where the click on the anchor i want to target happens -->
<nav>
<h2 class="wb-inv">Promotions</h2>
<ul class="toc lst-spcd col-md-12">
<li class="col-md-4">
Anchor for section 1
</li>
</nav>
<!-- below is the section of the same page the anchors would point to -->
<div class="col-md-12 pull-left">
<h2 id="story1">Section 1 Title </h2>
<p>Random paragraph 1</p>
</div>
<!-- The html I'm working with contains a set of tabs that reveal information as you click them, the href attribute and the id are both in the anchor. This is an example of anchors I wouldn't want to track-->
<a tabindex="-1" id="details-panel1-lnk" role="tab" aria-selected="false" aria-controls="details-panel1" href="#details-panel1">
<h2 class="h5 mrgn-tp-sm mrgn-bttm-sm">Online</h2>
</a>
Anchors that navigates to element on page is logged.
$(document).ready(function() {
var anchor = $("a[href^=\\#]");
var url = $(window);
anchor.on("click", function(e){
if ( $('#' + $(this).text()).length ) {
console.log($(this).text());
}
});
})
.section {
height: 400px;
}
.section:nth-child(even) {
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section" id="one">
one
</div>
<div class="section" id="two">
two
</div>
<div class="section" id="three">
three
</div>
<div class="section" id="four">
four
</div>
var anchor = $("a[href^=\\#]").not("a[href=#shr-pg0]");
anchor.on("click", function(){
var anchorText = this.text;
$(window).one("hashchange",function() {
console.log(anchorText);
});
});

jQuery: Find occurence/position of class on page

I am trying to find the occurence/position of a clicked class on the page.
HTML:
<div class="myclass"></div> <!-- OCCURENCE #1 -->
<div class="myclass"></div> <!-- OCCURENCE #2 -->
<div class="myclass"></div> <!-- OCCURENCE #3 -->
<div class="myclass"></div> <!-- OCCURENCE #4 -->
<div class="myclass"></div> <!-- OCCURENCE #5 -->
<div class="myclass"></div> <!-- OCCURENCE #6 -->
jQuery:
$('.myclass').click(function(event) {
//OUTPUT 'This class is the X one on the page'
});
For example if I click on the class occurence #3, I want to know that this class is the 3rd one on the page. I dont want to add any other infos such as data-id or id tag. How can I do that using jQuery? I know that I can get the total number of time the class is found using .length but that's about it.
You should use .index():
$(".myclass").click(function(e) {
var index = $(".myclass").index(this) + 1;
});
DEMO: http://jsfiddle.net/gdcQv/

JS Reveal/Hide toggle

Just a quick one, hopefully. I've coded up this:
<script>
$("div.design-project").css('display', 'none');
function InsertContent(tid) {
if(document.getElementById(tid).style.display == "none") {
document.getElementById(tid).style.display = "block";
}
else {
document.getElementById(tid).style.display = "none";
}
}
</script>
Which, if a link has the href:
href="javascript:InsertContent('design-project-1');"
it displays that div below. And if you click it again it disappears. Then if you click another link that say has the href:
href="javascript:InsertContent('design-project-2');"
it'll display that div and so forth.
However, if you have one div open, and click on another anchor link to open another div, it doesn't close the one already open.
Any ideas? Also, if there's a better way to do this then please let me know.
Thanks,
R
Here is the HTML as requested:
<a class="design-projects-slides-title" href="javascript:insertDesignProjectContent('design-project-1');">Title of project</a>
<!-- start of .design-project --><div class="design-project" id="design-project-1">
<div class="grid_6"><div class="project-info-area">
<h2>Title of project</h2>
<p>A rural retreat in the city. Built almost entirely from reclaimed element this little new-build timber cabin provides guest accommodation.<p>
<p>By coincidence a former chapel partition was found that matched the dimensions required. Used in their original painted condition, these doors became the front elevation and concertina open to one side - perfect for warm summer days. Further reclaimed elements include a bespoke curtain made from found patchwork, Victorian conservatory grills fitted over modern french heaters and industrial lights, taps, wash basin and an exposed shower fitting. Salvaged hardwood strip flooring and our Heathrow Terminal 2 stone fold from the floor to the walls. A thorough use of salvage all round!</p>
</div></div>
<div class="grid_6 project-info-images"><img src="http://placehold.it/460x540"></div>
<div class="grid_6 project-info-images"><img src="http://placehold.it/460x540"></div>
<div class="grid_6 project-info-images"><img src="http://placehold.it/460x540"></div>
<div class="grid_12 project-info-images"><img src="http://placehold.it/940x540"></div>
<div class="grid_6 project-info-images"><img src="http://placehold.it/460x540"></div>
<div class="grid_6 project-info-images"><img src="http://placehold.it/460x540"></div>
</div><!-- end of .design-project -->
UPDATE
In the end, I used a combination of your answers - thanks!
<!-- Reveal/hide sections on design projects/joinery -->
<script>
/* This is for the 'choose a project' reveal/hide */
$("div.slider-content").css('display', 'block');
$(".design-projects-slides-title").click(function() {
$(".slider-content").hide();
});
/* This is for reveal/hide on the product content */
$(".design-project").hide()
$('.design-projects-slides-title').click(function(){
var id = $(this).attr('id')
var content_id = id+"-content"
$('#'+content_id).slideDown('slow')
});
$(".slider-trigger").click(function() {
$(".design-project").hide();
});
</script>
First of all i see that you use jQuery so why not use it to achieve the entire flow?
You could do something like:
$(".mydivclass").click(function(){
$(".mydivclass").hide();
$(this).show();
})
Use jQuery toggle to achieve what you are trying to do. e.g.
function InsertContent(tid) {
$('#'+tid).toggle()
}
Another improvement you should do is that instead of hardcoding the id in each href, just add a class to element, override onclick of element and toggle related content. To get related content you can use a nomenclature e.g. if you use id='myid' for anchor, use id="myid_content" for content, so in click function you can toggle content e.g.
HTML:
<a class="content-link" id="myid">click me</a>
<div id="myid_content">
Here is the content
</div>
JavaScript:
$('.content-link').click(function(){
var id = $(this).attr('id')
var content_id = id+"_content"
$('#'+content_id).toggle()
}
Here is a working sample on jsFiddle
Better still is to keep clickable link and content inside a div, so that you don't need to set id, just set some classes and with parent and child relations you can get what is content e.g.
HTML
<div class="content-wrap">
<a class="content-link" >Click Me</a><br/>
<div class="content">
Here is the content for click me
</div>
</div>
JavaScript:
$('.content-link').click(function(){
var id = $(this).parent().find(".content).toggle()
})​
See it in action here
HTML
<a id="id1" href="#" rel="divContent1" >First</a><br/>
<a id="id2" href="#" rel="divContent2">Second</a><br/>
<div id="divContent1" class="content">
Content of Div 1
</div>
<div id="divContent2" class="content">
Content of Div2
</div>​
Javascript
$(function(){
$(".content").hide();
$("a").click(function(e){
e.preventDefault()
var divToShowId=$(this).attr("rel");
$(".content").hide();
$("#"+divToShowId).show();
});
})​
I used the id of Content divs as the rel attribute value of links as we need some way to connect a link with its content.
Here is the working demo : http://jsfiddle.net/Kx9Ma/5/

selecting span value inside div

Let's say I have
<div id="1">
<span id="name">Josh</span>
<div id="quote">Run</div>
</div>
<div id="2">
<span id="name">Mark</span>
<div id="quote">Run</div>
</div>
How would I select the name between the span tags from the first div?
$("#quote").click(function(){
var name = $('#name').html();
});
Firstly, id's have to be unique in an html document. So,ideally, you need to change those id's within the div to a class. Secondly, id's cannot begin with a numeric, so you need to change your div id's to start with a letter or underscore.
With that in mind, given this structure:
<div id="one">
<span class="name">Josh</span>
<div class="quote">Run</div>
</div>
<div id="two">
<span class="name">Mark</span>
<div class="quote">Run</div>
</div>
you would be looking for:
$("#quote").click(function(){
var name = $('#one .name').html();
});
id's should be unique across a page. You should change the name and quote id's to a class, which do not have to be unique.
<div id="1">
<span class="name">Josh</span>
<div class="quote">Run</div>
</div>
<div id="2">
<span class="name">Mark</span>
<div class="quote">Run</div>
</div>
You could then select via:
$('#1 .name')
You should also bare in mind that id's should not start with a number (except in HTML5)
var name = $("#1 span").html()
or
var name = $('#1 #name').html();
this should work for you:
$("#1 span").text();
You have some problems with your HTML though. You should not have any duplicate IDs in your HTML, they must be unique. ID shouldn't start with a number either.
You can view the fiddle here: http://jsfiddle.net/
you can select the first span tag content of your div #1 this way as well :
var name = $("#1 span:first").html();
Adding #1 before #name would select the first div
$("#quote").click(function(){
var name = $('#1 #name').html();
});

Categories

Resources