Get the ID of clicked element and use it as $(this) - javascript

I need to be able to click an element, get the ID of that element and use it on another function. How can I do it as It is not working using $(this). This is what I have so far:
$("#pills-ficha").on("click", closePillsOnClick);
function closePillsOnClick() {
var clickedId = $(this).attr("id");
var clickedIdChild = $(this).html($(this).html().split("By:").join(""));
if ($(clickedId).hasClass("active")) {
$(clickedId).removeClass("active show");
e.stopPropagation();
$(clickedIdChild).removeClass("active show").css("display", "none");
} else {
$(clickedIdChild).css("display", "block");
$(clickedIdChild).siblings().css("display", "none");
}
}
/* edit */
I'll add the markup:
<div class="d-flex flex-nowrap align-items-center">
<ul id="examples" class="nav nav-pills justify-content-center justify-content-lg-start" role="tablist">
<span class="text-blue font-weight-medium">EJEMPLOS:</span>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" id="pills-ficha-tab" data-toggle="pill" href="#pills-ficha" role="tab" aria-controls="pills-ficha" aria-selected="false">Ficha</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" id="pills-candidato-tab" data-toggle="pill" href="#pills-candidato" role="tab" aria-controls="pills-candidato" aria-selected="false">Mail candidato</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" id="pills-empresa-tab" data-toggle="pill" href="#pills-empresa" role="tab" aria-controls="pills-empresa" aria-selected="false">Mail empresa</a>
</li>
</ul>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-8 offset-lg-2 text-center tab-content" id="pills-tabContent">
<div class="tab-pane fade" id="pills-ficha" role="tabpanel" aria-labelledby="pills-ficha-tab">
<img src="img/gold/gold-ejemplo-ficha.jpg" alt="Ejemplo de ficha">
</div>
<div class="tab-pane fade" id="pills-candidato" role="tabpanel" aria-labelledby="pills-candidato-tab">
<img src="img/gold/gold-ejemplo-candidato.jpg" alt="Ejemplo de mail al candidato">
</div>
<div class="tab-pane fade" id="pills-empresa" role="tabpanel" aria-labelledby="pills-empresa-tab">
<img src="img/gold/gold-ejemplo-empresa.jpg" alt="Ejemplo de mail a la empresa">
</div>
</div>
</div>

The main issue with your logic is because attr('id') is returning you back pills-ficha, which in itself is not a valid selector. You would need to append # to it for it to work.
However this is a flawed approach. You already have the reference to the element itself through the this keyword. Creating a reference to that element to get its id to then get another reference to the same element by that id is entirely pointless.
As such, you can simplify the logic like this:
$("#pills-ficha").on("click", closePillsOnClick);
function closePillsOnClick() {
var $clicked = $(this);
var clickedIdChild = $clicked.html($clicked.html().split("By:").join(""));
if ($clicked.hasClass("active")) {
e.stopPropagation();
$clicked.removeClass("active show");
$(clickedIdChild).removeClass("active show").hide();
} else {
$(clickedIdChild).show().siblings().hide()
}
}
It's likely you can do the same with the clickedIdChild reference, but your HTML doesn't show enough information for me to give you an example of how to fix that.

The problem with my original question was this part:
var clickedIdChild = $(this).html($(this).html().split("By:").join(""));
It had to be:
var clickedIdChild = clickedId.split(":By").join("");
Also adding:
$("#"+clickedIdChild) as a selector.
Then this works as expected:
function closePillsOnClick(e){
var clickedId = $(this).attr("id");
var clickedIdChild = clickedId.split("-tab").join("");
if( $(this).hasClass("active") ){
$(this).removeClass("active show");
e.stopPropagation();
$("#"+clickedIdChild).removeClass("active show").css("display", "none");
} else {
$("#"+clickedIdChild).css("display", "block");
$("#"+clickedIdChild).siblings().css("display", "none");
}
};

OK let's clarify this. var clickedId = $(this).attr("id"); will return ID in the form fakeId. Next you have a jQuery with with the ID ($(clickedId)) which will be $('fakeId') in my example. ID selector needs to start with # so you have to add it. So valid code will be $('#' + clickedId). More here:
http://api.jquery.com/id-selector/
https://api.jquery.com/attr
Cheers.

Related

Bootstrap Tabs with Next Arrow If Multiple tabs exist

I hope someone will be able to help me on this issue. I'm having hard time converting it to latest bootstrap 4 tabs.
Here's the source: https://codepen.io/srees/pen/pgVLbm
But the problem is that it used the bootstrap 3 version and it doesn't have tab content.
Basically what i need to do is this
If there's a multiple tabs you can click the arrow to slide to another tabs, just like in the browser
This is where i want to do
<li class="nav-item">
<a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">...</div>
<div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">...</div>
<div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">...</div>
</div>
I hope this will help you out
assign data-id to anchor tags with number like
HTML
Home
Home
Home
JQuery
$(document).ready(function(){
var maxTabs = $(".nav-item").length; //Get total number of Tabs
$("#next").click(function(e){
e.preventDefault();
var activeAnchor = $("ul").find("a").hasClass("active"); //Get a tag with class active
// OR you can use var activeAnchor = $("li > a").hasClass("active");
if(activeAnchor === true){ // check if any "a" has class "active"
$(this).removeClass("active"); // remove "active" class for current element
var current = $(this).attr("data-id"); // get the data-id of current element
if(current < maxTabs){ // checks if id is the last one
var nextId = current + 1; //adding 1 to current id to get the next element
$("#nextId").addClass("active"); //Adding the active class to next element
}
}
});
});
Please let me know if it works. I am not sure but maybe you encounter problem on line $(this).removeClass("active");. If you come across this issue. Please let me know I will provide an alternative solution.

How to select 2nd bootstrap tab on load of page?

EDIT: So i ditched the whole thing and resorted to javascript with these new codes #Udara Kasun's code worked and it was close but not what I was trying to achieve. tried these codes for a while and i think i almost got it.
<script>
function myFunction1()
{
$(document).ready(function()
{
$('.nav-tabs li:nth-child(1) a').tab('show')
});
}
function myFunction2()
{
$(document).ready(function()
{
$('.nav-tabs li:nth-child(2) a').tab('show')
});
}
function myFunction3()
{
$(document).ready(function()
{
$('.nav-tabs li:nth-child(3) a').tab('show')
});
}
</script>
<li role="presentation" class="active" id="tabMenu1" onclick="myFunction1()">
<a href="#tabZone" data-toggle="tab" role="tab" aria-controls="tab1">
Zones
</a>
</li>
<li role="presentation" id="tabMenu2" onclick="myFunction2()">
<a href="#tabChapels" data-toggle="tab" role="tab" aria-controls="tab2">
Chapels
</a>
</li>
<li role="presentation" id="tabMenu3" onclick="myFunction3()">
<a href="#tabUnits" data-toggle="tab" role="tab" aria-controls="tab3">
Units
</a>
</li>
Did you try to do like this?
$(document).ready(function(){
$('.nav-tabs a:last').tab('show') ;
var lastselectedtab = localStorage.getItem("ActiveTab");
$('.nav-tabs a[href="'+(lastselectedtab==''?"#tabChapels":lastselectedtab)+'"]').tab('show');
});
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(e.target).attr("href") // activated tab
localStorage.setItem("ActiveTab", target);
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div role="tabpanel">
<ul class="nav nav-tabs" role="tablist">
<li role="presentation">
Zones
</li>
<li role="presentation">
Chapels
</li>
</ul>
<div id="tabContent1" class="tab-content" style="font-family:Arial Unicode MS;">
<div role="tabpanel" class="tab-pane fade" id="tabZone">
Content 1
</div>
<div role="tabpanel" class="tab-pane fade in active" id="tabChapels">
Content 2
</div>
</div>
</div>
Code pen Link
https://codepen.io/udarakasun/pen/YdyRRy
Nobody seemed to care anymore haha anyways for those of you who are wanting to achieve the same thing that I wanted to, I've created a stupid and ingenious way but it works.
<script language="javascript">
<?php
if(isset($_GET['tabName']))
{
if($_GET['tabName']=="TAB1")
{
echo "var tabNo=1;";
$_SESSION['tabNo']=1;
}
elseif($_GET['tabName']=="TAB2")
{
echo "var tabNo=2;";
$_SESSION['tabNo']=2;
}
}
?>
function loadscript()
{
$(document).ready(function()
{
$('.nav-tabs li:nth-child('+<?php echo $_SESSION['tabNo'];?>+') a').tab('show')
});
}
function myFunction1()
{
var tabName="TAB1";
window.location.href = "panel_gkkmain.php?tabName=" + tabName;
}
function myFunction2()
{
$(document).ready(function()
{
$('.nav-tabs li:nth-child(2) a').tab('show')
});
var tabName="TAB2";
window.location.href = "panel_gkkmain.php?tabName=" + tabName;
}
function myFunction3()
{
var tabName="TAB3";
window.location.href = "panel_gkkmain.php?tabName=" + tabName;
}
and for the body, you have to declare onload="loadscript()"
After that you'll need to add bootstrap components to your page. This can be done easier through ADOBE DREAMWEAVER.
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active" onClick="myFunction1()">
<a href="#home1" data-toggle="tab" role="tab" aria-controls="tab1">
Zones
</a>
</li>
<li role="presentation" onClick="myFunction2()">
<a href="#paneTwo1" data-toggle="tab" role="tab" aria-controls="tab2">
Chapels
</a>
</li>

dynamically load file to html tab content

I am trying to load the tab contents dynamically from different html page. When I click EROs tab it should display the contents from /SVB/Tax_Eros.html file without reloading the page. Likewise when Import tab is clicked it should display the contents from /SVB/Tax_Imports
<ul class="nav nav-tabs">
<li class="active" >
EROs
</li>
<li>
Imports
</li>
<li>
Accounting
</li>
</ul>
<div class="tab-content clear-fix">
<div class="tab-pane active" id="eros">
<script>
$('#eros').click(function(){
$('#Taxeros').load($(this).attr('href'));
});
</script>
</div>
<div class="tab-pane" id="imports">
<script>
$('#imports').click(function(){
$('#Taximports').load($(this).attr('href'));
});
</script>
</div>
<div class="tab-pane" id="accounting">
<script>
$('#accounting').click(function(){
$('#Taxaccounting').load($(this).attr('href'));
});
</script>
</div>
</div>
Since you are using Bootstrap Tabs (3.3.7) you will need to modify your markup as Bootstrap expects certain conventions for it to do its magic without configuring a bunch of JS.
Instead of placing the page you need to load in the href attribute we place it in a custom data-src attribute. Bootstrap expects the value of the href attribute to be the ID of the tab pane associated with the tab. We also added data-toggle="tab" as that is required for Bootstrap Tabs to function.
It looked like you were trying to load content on tab click but that isn't useful for the default tab and it's tab pane as there won't be any content in it initially. So we've passed a function to jQuery that will get executed when the DOM is ready. This function will parse the tabs and load content into the tab panes based on the attribute values.
$(function() {
$('.nav-tabs a').each(function(index, el) {
var $this = $(this);
var pane = $this.attr('href');
var src = $this.data('src');
$(pane).load(src);
});
});
<ul class="nav nav-tabs">
<li class="active">
<a data-src="/SVB/Tax_Eros" href="#eros" data-toggle="tab">EROs</a>
</li>
<li>
<a data-src="/SVB/Tax_Imports" href="#imports" data-toggle="tab">Imports</a>
</li>
<li>
<a data-src="/SVB/Tax_Accounting" href="#accounting" data-toggle="tab">Accounting</a>
</li>
</ul>
<div class="tab-content clear-fix">
<div class="tab-pane active" id="eros">1</div>
<div class="tab-pane" id="imports">2</div>
<div class="tab-pane" id="accounting">3</div>
</div>
As far as I know, Stack Snippets cannot mock Ajax requests so here's a JSFiddle and a Plunker that do.
$(function() {
$('.nav-tabs a').each(function(index, el) {
var $this = $(this);
var pane = $this.attr('href');
var src = $this.data('src');
$(pane).load(src);
});
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<ul class="nav nav-tabs">
<li class="active">
<a data-src="/SVB/Tax_Eros" href="#eros" data-toggle="tab">EROs</a>
</li>
<li>
<a data-src="/SVB/Tax_Imports" href="#imports" data-toggle="tab">Imports</a>
</li>
<li>
<a data-src="/SVB/Tax_Accounting" href="#accounting" data-toggle="tab">Accounting</a>
</li>
</ul>
<div class="tab-content clear-fix">
<div class="tab-pane active" id="eros">1</div>
<div class="tab-pane" id="imports">2</div>
<div class="tab-pane" id="accounting">3</div>
</div>
<html>
<head>
<script type='text/javascript'>
function clicks () {
var myButtons = document.querySelectorAll('.eros') || null;
if (myButtons != null){
for (var i = 0; i < myButtons.length; i++){
myButtons[i].addEventListener('click', function () {
var url = this.getAttribute('data-href'); // location to load
var obj = this.getAttribute('data-id');//id to append content
var type = 'GET'; /*-> post or get-> if is 'post' page must be in Php or other server language*/
data = '';
var objElm = document.querySelector('#'+obj) || null;
if (objElm === null){console.log('no element to write content'); return;}
xmlRequest (url, type, data, obj)
}, !1);
}
}
}
function xmlRequest (url, type, data, obj){
var xhr = new XMLHttpRequest || null;
if (chr === null){console.log('Obsolete browser');return;}
xhr.addEventListener('load', function () {
if (this.status == 200 && this.readyState == 4){
obj.innerHTML = this.responseText;
}
else {console.log('Error')}
}, !1);
xhr.open(type, url);
xhr.setRequestHeader('Content-type', 'Application/x-www-form-urlencoded');
xhr.send(data)
}
</script>
<script type='text/javascript'>
window.addEventListener('load', function () {
clicks ();
}, !1)
</script>
</head>
<body>
<ul class="nav nav-tabs">
<li class="active" >
<a data-href="/SVB/Tax_Eros" data-toggle="tab" data-id="eros" class="eros">EROs</a>
</li>
<li>
<a data-href="/SVB/Tax_Imports" data-toggle="tab" data-id="imports" class="eros">Imports</a>
</li>
<li>
<a data-href="/SVB/Tax_Accounting" data-toggle="tab" data-id="accounting" class="eros">Accounting</a>
</li>
</ul>
<div class="tab-content clear-fix">
<div class="tab-pane active" id="eros"> </div>
<div class="tab-pane" id="imports"></div>
<div class="tab-pane" id="accounting"></div>
</div>
</body>

Check if Bootstrap tab-content is scrolled to end

I have created bootstrap tab and their corresponding tab-content as per http://getbootstrap.com/javascript/#tabs
The html snippet is given below.
<ul class="nav nav-tabs nav-justified">
<li class="active" role="presentation">
<a href="#tab1" data-toggle="tab" aria-controls="tab1" role="tab">
</li>
<li>
<a href="#tab2" data-toggle="tab" aria-controls="tab2" role="tab">
</li>
</ul>
<div class="tab-content">
<ul class="list-group media-list media-list-stream tab-pane active" id="tab1" role="tabpanel">
</ul>
<ul class="list-group media-list media-list-stream tab-pane" id="tab2" role="tabpanel">
</ul>
</div>
How to check if the tab-content has been scrolled to it's bottom.
The usual solution as mentioned in https://www.sitepoint.com/jquery-check-div-scrolled/ doesn't seem to work.
$(document).ready(function(){
$(tab1).bind('scroll',chk_scroll);
});
function chk_scroll(e)
{
var elem = $(e.currentTarget);
if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight())
{
console.log("bottom");
}
}
I have two solution for your answer.
Check the example code here CODEPEN.
1. If you do not fix the height of tab-content div then try this code(don't include CSS):
JS:
$(window).scroll(function() {
if (isScrollBottom()) {
alert('scroll end');
}
});
function isScrollBottom() {
var documentHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
return (documentHeight == scrollPosition);
}
2. If you fix the height of tab-content, the try this code:
JS:
$("#myTabContent").scroll(function (e) {
e.preventDefault();
var elem = $(this);
if (elem.scrollTop() > 0 &&
(elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight())) {
alert("At the bottom");
}
});
CSS:
.tab-content {
height:150px;/*set height here*/
overflow:auto;
}
I hope this resolves your issue.
Enjoy :)

Show the content based on link click. And hide previously selected

I want to show the content based on link click. and hide the content which was previously selected.
Any way to do it?
Note : I dont want to change the markup.
Here is jsFiddle
html:
<ul class="nav nav-stacked" id="nav-stacked">
<li class="active"><i class="fa fa-dashboard fa-fw"></i>Dashboard
</li>
<li id="vollist-container" class="menu open"><i class="fa fa-sort-alpha-asc fa-fw"></i>Volumes<i class="caret"></i>
<ul id="vol-list" class="submenu">
<li> <a href="javascript:void(0);" onclick="show_content('vol1', this)">
<span>vol1</span>
</a>
</li>
<li> <a href="javascript:void(0);" onclick="show_content('vol2', this)">
<span>vol2</span>
</a>
</li>
</ul>
</li>
</ul>
<div id="content">
<div id="dashboard" class='show'>dashboard</div>
<div id="volumes">
<div id="vol1" class="hide">vol 1</div>
<div id="vol2" class="hide">vol 2</div>
</div>
</div>
jQuery:
function show_content(id, element) {
var children = $("#content").children();
children.filter(function () {
return $(this).css('display') == 'block';
}).hide();
$("#" + id).parent().css('display') == 'none' ? $("#" + id).parent().show() : null;
$("#" + id).toggleClass('hide');
}
This function does what you need:
function show_content(id, element) {
$('#content > div').hide();
$('#' + id).show();
}
Notes:
You do not need the .show and .hide CSS classes
You still need to hide all the content divs on page load either via CSS or via jQuery.
The element parameter is not necessary.
jQuery offers more elegant ways to solve this problem, but the function above should answer your question.
<script>
function showSomething()
{
$("#div1").hide();
$("#div2").show();
</script>
Around your div:
<a href="Javascript:showSomething();">
<div></div>
</a>

Categories

Resources