Create a variable that contains the id of clicked div - javascript

Does anybody have any idea how to create a variable that contains the id of a clicked div?
I want to hide all the #content-wrappers on page load apart from the first one then when the .square has been clicked for it to display the div with the same class as the id that has been clicked, it doesn't make much sense when you write id down but if you look at my fiddle then it should hopefully make sense?
http://jsfiddle.net/alexjamest/Lkaxza22/
$('#content-wrapper').hide();
$(".square").click(function() {
var id_name= $(this).attr(id);
if $('#content-wrapper').hasClass(id_name){
$(this).fadeIn();
}
});
<div id="content-wrapper" class="c1">Content 1</div>
<div id="content-wrapper" class="c2">Content 2</div>
<div id="content-wrapper" class="c3">Content 3</div>
<div id="content-wrapper" class="c4">Content 4</div>
<div id="content-wrapper" class="c5">Content 5</div>
<div id="content-wrapper" class="c6">Content 6</div>
<div id="content-wrapper" class="c7">Content 7</div>
<div id="content-wrapper" class="c8">Content 8</div>
<div class="square" id="c1"></div>
<div class="square" id="c2"></div>
<div class="square" id="c3"></div>
<div class="square" id="c4"></div>
<div class="square" id="c5"></div>
<div class="square" id="c6"></div>
<div class="square" id="c7"></div>
<div class="square" id="c8"></div>

Change your content-wrappers elements so that they contain classes, not ids, since ids should be unique. You can, however, identify your content with some sort of a prefix, like content-:
<div class="content-wrapper" id="content-c1">Content 1</div>
<div class="content-wrapper" id="content-c2">Content 2</div>
<div class="content-wrapper" id="content-c3">Content 3</div>
<div class="content-wrapper" id="content-c4">Content 4</div>
<div class="content-wrapper" id="content-c5">Content 5</div>
<div class="content-wrapper" id="content-c6">Content 6</div>
<div class="content-wrapper" id="content-c7">Content 7</div>
<div class="content-wrapper" id="content-c8">Content 8</div>
Then the following code will work:
$(document).ready(function()
{
$(".content-wrapper").hide();
$(document).on("click", ".square", function()
{
var id = $(this).attr("id");
$("#content-"+id).fadeIn();
});
});
Note the following part
$(".content-wrapper").hide();
which is important, since we're identifying that we wish to hide all elements which contain the class content-wrapper, not the id content-wrapper.
Working Demo.

There are four problems with your code:
$('#content-wrapper').hide(); will only hide the first element with that ID, because IDs have to be unique. Use a common class instead.
var id_name= $(this).attr(id);. id is an undefined variable. You probably want to pass the string "id" instead, or better, just access the property of the DOM element: this.id.
if $('#content-wrapper').hasClass(id_name){ is a syntax error. The condition has to be put in parhenthesis:
if ($('#content-wrapper').hasClass(id_name)) {
However, that alone won't make the condition work, since again, #content-wrapper will only select the first element. Just select the corresponding element by class:
$('.' + this.id).fadeIn();
You can also add .content-wrapper for more granular filtering:
$('.content-wrapper.' + this.id).fadeIn();
Fixed code:
$('.content-wrapper').hide(); // give that class to all elements instead of the ID
$(".square").click(function() {
$('.' + this.id).fadeIn();
});
DEMO

A JQuery-less solution, still with the fade animation.
On load it gets an array of buttons and an array of content wrappers, then it just uses the order to figure out which box to reveal. Will only work with an equal number of buttons and wrappers. I started the wrappers as invisible in the style sheet, so we only have to reveal them. Also remembers which buttons was clicked last and resets its visibility.
<head>
<style>
.content-wrapper{
opacity:0;
transition:opacity 1s ease;/* only showing the normal one, prefixed may be required for portability*/
}
</style>
<script>
window.addEventListener('load',onload,false);
var wrappers;
var buttons;
var last;
function onload(){
wrappers = document.getElementsByClassName('content-wrapper');
buttons = document.getElementsByClassName('square');
var i = buttons.length;
while(i--) // add listener for each button
buttons[i].addEventListener('click',onclick,false);
}
function onclick(){
if(last)wrappers[last].style.opacity = '0.0'; //hide previous
var i = buttons.indexOf(this);
wrappers[i].style.opacity = '1.0'; //show clicked
last = i;
}
</script>
</head>
<body>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='content-wrapper'></div>
<div class='square'></div>
<div class='square'></div>
<div class='square'></div>
<div class='square'></div>
<div class='square'></div>
</body>

Related

Get first three child elements of parent with jQuery

I want to get the first 3 elements in a div, so e1, e2 and e3:
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
I want to do this with jQuery. What's the best way to achieve this?
Actually you can do this with nth-child pseudo-class with functional notation. So this will work like:
:nth-child(-n+3)
Represents the first three elements. [=-0+3, -1+3, -2+3]
Where the functional notation represents elements in a list whose indices match those found in a custom pattern of numbers, defined by An+B, where:
A is an integer step size,
B is an integer offset,
n is all positive integers, starting from 0.
So your final code would be something like:
const elements = document.querySelectorAll('#parent > div:nth-child(-n+3)')
elements.forEach(element => {
console.log(element.id)
})
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
But if you want to stick with jQuery itself you can use jQuery :lt() instead. Where jQuery( ":lt(index)" ) Select all elements at an index less than index within the matched set
The output will be something like this:
const elements = $('#parent > div:lt(3)')
jQuery.each(elements, function (index, element) {
console.log(element.id)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<div id="e1">element 1</div>
<div id="e2">element 2</div>
<div id="e3">element 3</div>
<div id="e4">element 4</div>
</div>
You can use jQuery's .each() function and a little conditional if statement with the function's index...
$('#parent').children().each(function(index){
// To counteract the zero-based index.
index++
if (index < 4) {
console.log(this);
}
});
Example on Codepen

How to get element position in hidden tab-panel?

There is a script that works fine if the tab-panel is not hidden, but I need to count position, width of the element without to do action with tab-panel display , because that script i use beyond tab-panel like only ".swipeTab".
P.S. Sorry for my English ...
For example:
<div class="tab-panel" style="display: none">
<div class="swipeTab">
<div class="swipeTab__list">
<div class="swipeTab__item">TAB 1</div>
<div class="swipeTab__item">TAB 2</div>
<div class="swipeTab__item">TAB 3</div>
<div class="swipeTab__item">TAB ...</div>
</div>
</div>
</div>
Part of script
var target = $('.swipeTab__item'),
list= $('.swipeTab__list');
position: function(target) {
return {
left : $(target).position().left,
right : parseInt($(list).outerWidth()) - parseInt($(target).position().left) - parseInt($(target).outerWidth())
}
}

Ignore visibility of outer elements and select the first visible child element in a jQuery selector

HTML:
<div class="outer">
<div id="inner1" class="inner" style="display: none"></div>
<div id="inner2" class="inner"></div>
<div id="inner3" class="inner"></div>
</div>
JavaScript (fiddle):
var $first_visible = $("div.inner:visible:first");
This returns the first visible inner div, which is inner2.
However, as soon as the outer div is hidden (let's say I want to fade it in at some later time):
<div class="outer" style="display: none">
<div id="inner1" class="inner" style="display: none"></div>
<div id="inner2" class="inner"></div>
<div id="inner3" class="inner"></div>
</div>
all inner divs are considered hidden and the selector does not return inner2 any more.
How would I need to modify my jQuery selector to ignore the container's visibility?
As adeneo said, once its hidden, there isnt much you can do.
However, you can check before hand, show it regardless, then hide it again if it was hidden
var wasVisible = $(".outer").is(':visible');
$(".outer").show();
var $first_visible = $("div.inner:visible:first");
if (!wasVisible) {
$(".outer").hide();
}
console.log($first_visible.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="outer" style="display: none">
<div id="inner1" class="inner" style="display: none"></div>
<div id="inner2" class="inner"></div>
<div id="inner3" class="inner"></div>
</div>
MDN says:
When you use none, all descendant elements also have their display turned off. The document is rendered as though the element doesn't exist in the document tree.
Hence, whatever the HTML elements are child to the parent element will not be rendered in the HTML page.
And moreover, whatever styles that has been applied on the parent element will not be rendered in HTML page.
In order to achieve what you want and if you consider that your HTML element should be in the document tree then try using CSS visibility property. For example:
<div class="outer" style="visibility: hidden">
<div id="inner1" class="inner" style="display: none"></div>
<div id="inner2" class="inner" style="visibility: visible"></div>
<div id="inner3" class="inner"></div>
</div>
JS Fiddle
If I understood you correctly, you can simulate the effects of the parent being hidden using CSS like this.
HTML
<div class="outer hide">
<div id="inner1" class="inner hide">Inner 1</div>
<div id="inner2" class="inner">Inner 2</div>
<div id="inner3" class="inner">Inner 3</div>
</div>
CSS
.hide {
background: rgba(0,0,0,0);
color: rgba(0,0,0,0);
border-color: rgba(0,0,0,0);
// For an SVG
fill: rgba(0,0,0,0);
stroke-opacity: 0;
}
The reason why you can't use the visibility/display/opacity property is because as #Umesh mentioned that the all descendant elements will also get their display/visibility/opacity as not visible as if the element doesn't exist in the document tree.
But using this method you set the alpha to 0 of the element and this doesn't effect the descendants unless they have inherit set for those properties.
Hope this helps.
write two classes : first one to display and last one to hide.
With that you can select all divs whoses "visible" even if parent is "hidden"
var $first_visible = $("div.inner.enable");
console.log($first_visible);
$("div#result").text($first_visible[0].id);
.disable{
display : none;
}
.enable{
display : block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer disable">
<div id="inner1" class="inner disable">1</div>
<div id="inner2" class="inner enable">2</div>
<div id="inner3" class="inner enable">3</div>
</div>
<div id="result"></div>
One option would be to show the parent element, check for the first visible element, and then hide the parent element again.
Alternatively, since the element has inline CSS, you could filter the elements based on whether the display property is set to none and then retrieve the first one in the filtered collection:
Updated Example
var $first_visible = $(".inner").filter(function () {
return this.style.display !== 'none';
}).first();
var $first_visible = $(".inner").filter(function () {
return this.style.display !== 'none';
}).first();
$("div#result").text('First visible: #' + $first_visible[0].id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer" style="display: none;">
<div id="inner1" class="inner" style="display: none"></div>
<div id="inner2" class="inner"></div>
<div id="inner3" class="inner"></div>
</div>
<div id="result"></div>
However, the better approach would be to check the computed style of the element using the .getComputedStyle() method. In doing so, you can determine whether the display of the element is set to none even if the element doesn't have inline CSS.
Updated Example
var $first_visible = $(".inner").filter(function () {
return window.getComputedStyle(this, null).getPropertyValue('display') !== 'none';
}).first();
var $first_visible = $(".inner").filter(function () {
return window.getComputedStyle(this, null).getPropertyValue('display') !== 'none';
}).first();
$("div#result").text('First visible: #' + $first_visible[0].id);
#inner1 { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer" style="display: none;">
<div id="inner1" class="inner"></div>
<div id="inner2" class="inner"></div>
<div id="inner3" class="inner"></div>
</div>
<div id="result"></div>
My proposal is to use a filter function but only to select the first visible element (but this is also hidden because the parent is hidden):
var $first_visible = $('div.inner').filter(function() {
return !(this.style.visibility != '' || this.style.display != '');
}).first();
$(function () {
var $first_visible = $('div.inner').filter(function() {
return !(this.style.visibility != '' || this.style.display != '');
}).first();
$('body').append('<p>' + $first_visible.attr('id') + '</p>');
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<div class="outer" style="display: none">
<div id="inner1" class="inner" style="display: none;"></div>
<div id="inner2" class="inner"></div>
<div id="inner3" class="inner"></div>
</div>
See here i have checked style attribute for ignore first div. And check with hidden selector for get all other div.
$(document).ready(function(){
var currElements=$('.inner[style!="display: none"]:hidden'); // Here you are get two div with id inner2 and inner3
alert(currElements[0].id); // First div
alert(currElements[1].id); // First div
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer" style="display: none">
<div id="inner1" class="inner" style="display: none">Inner 1</div>
<div id="inner2" class="inner">Inner 2</div>
<div id="inner3" class="inner">Inner 3</div>
</div>
Take a flag value and loop each div.inner to get first visible element. Then check its css property.
Below is the tested code :
var isValid=true;
$("div.inner").each(function() {
if($(this).css("display") == "block" && isValid) {
$("div#result").text($(this).attr('id'));isValid=false;
}
});

jQuery getting element index despite wrapper / parent element?

I have divs with same class, but each 3 are wrapped in a parent div. I can't get the index the way I want it. I am sorry, could anyone help me to get the index as number from 0 to 8.. when i click on any element? despite the parent element.
Here is my full code for your testing.
<div class="more-content">
<div class="post">post 1</div>
<div class="post">post 2</div>
<div class="post">post 3</div>
</div>
<div class="more-content">
<div class="post">post 4</div>
<div class="post">post 5</div>
<div class="post">post 6</div>
</div>
<div class="more-content">
<div class="post">post 7</div>
<div class="post">post 8</div>
<div class="post">post 9</div>
</div>
<script type="text/javascript">
$(function() {
// navigate posts with next/prev buttons
$(".post").click(function(){
alert($(this).index());
});
});
</script>
If i click i get index 0, 1, 2 ..i think because each 3 items are wrapped in parent? I am new with jquery, any help appreciated. what i need is get the index of post with same class.. say post 6 = index 5.. and so on
UPDATE
How can I get the same result if the clicked element is a child anchor in the post div and not the post div directly?
Try index method with this as an argument:
$(".post").click(function() {
alert($(".post").index(this));
});​
DEMO: http://jsfiddle.net/Nryf3/
var posts = $('.post').click(function(){
alert(posts.index(this));
});
DEMO: http://jsfiddle.net/paZ2e/
You could loop through all elements tagged post and increment a counter until you find the object you're looking for, like this:
$(".post").click(function() {
var counter = 0;
var that = this;
$(".post").each(function() {
if(that == this) break;
counter++;
}
// counter now equals the index of the post element out of all posts on the page
});

JavaScript Show/Hide as Filters to list of divs

Looking to create Javascript that acts like a filter on a list of divs.
For instance, here's the intended markup...
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
I want to be able to click on the link for Item 1, and show only Item 1 divs and hide all other divs, click the link of Item 2, and show only Item 2 divs and hide all other divs and so on. I've seen several similar scripts but nothing that seemingly turns divs matching the class on/off in this manner.
This can be done easily in Jquery, following should work for you, but you have to modify your html as following
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
and javascript as follows
$(document).ready(function(){
$(".link").click(function(e){
$("." + e.currentTarget.id).toggle()
}
});
You can use jQuery's toggle. below is simple example:
$(document).ready(function() {
$('#IDOfLink').click(function() {
$('.class1').toggle("slow");//switch to show/hide when clicked
//hide other div u wish
});
$('#anotherLinkID').click(function() {
$('.class2').toggle("fast");//switch to show/hide when clicked
//hide other div u wish
});
//...etc...
});
Very simple solution:
Filter Item 1
This, ofcourse, will hide all the other div's on page, so you should give the all some other class or put inside another div. Then the code could be:
Filter Item 1
<div id="filtered">
<div class="1"></div>
...
</div>
Set an ID for each link, then assign an onclick event. There you can filter out divs using the clicked link ID.
Something like this (http://jsfiddle.net/pJRek/1/)
Markup:
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
<div class="group_1">Item 1</div>
<div class="group_1">Item 1</div>
<div class="group_2">Item 2</div>
<div class="group_3">Item 3</div>
<div class="group_1">Item 1</div>
<div class="group_4">Item 4</div>
<div class="group_4">Item 4</div>
<div class="group_1">Item 1</div>
<div class="group_5">Item 5</div>
And script:
$(document).ready(function(){
var links = $('.bound');
var divs = $('div');
links.click(function(event){
divs.hide();
divs.filter('.' + event.target.id).show();
});
});
If you setup your HTML as:
<div id="controls">
Filter Item 1
Filter Item 2
Filter Item 3
Filter Item 4
Filter Item 5
</div>
<div id="items">
<div class="1">Item 1</div>
<div class="1">Item 1</div>
<div class="2">Item 2</div>
<div class="3">Item 3</div>
<div class="1">Item 1</div>
<div class="4">Item 4</div>
<div class="4">Item 4</div>
<div class="1">Item 1</div>
<div class="5">Item 5</div>
</div>
Then your jQuery code can be as simple as:
$(function(){
$("#controls a").click(function() {
$("#items").find("." + this.id).toggle();
});
});
Of course, you will want to add a visual indication that a filter is toggled on and off.
You may not want to associate the items with each link through id/classes, but instead use jQuery's data storage, depending on your needs.
A working example, tested in firefox, here: http://jsfiddle.net/mwolfetech/GetRV/
Edit: This solution is similar to Anto Binish Kaspar's, mainly differing only in
how the html is modified. I think that the divs given are likely to be a good structure for your document anyway, and eliminates the need for extra classes for control. This is always a design decision--balancing div (for structural division) vs class (for, categories). Additionally, theres no need to extract the id from the event object as jQuery provides the this reference.
Give them all another class (for example item) and then make the click hide all item and show all of the selected value.

Categories