How to get a value of inner element when clicked on li using JQuery - javascript

This is my li element. I want to get only the value of class 'preview' when clicking on the li element using jquery.
<li class="contact">
<div class="wrap">
<span class="contact-status online"></span>
<img src="" alt="" width="45px" height="45px" />
<div class="meta">
<p class="name">John</p>
<p class="preview">john#gmail.com</p>
</div>
</div>
</li>
Output should be: john#gmail.com
I tried below code:
$('li.contact').on("click", function(e) {
e.preventDefault();
var data = $('.preview').val($(this).text());
})
Am getting the entire li items click event list as output.
Please help on this. Thanks.

You'd want to attach the click event handler to each list node, then a few ways could find the child nodes text value, one approach would be using the event.target to get access to the clicked list node, or my approach would be iterating over the list node collection as the following example illustrates.
const theLinkContains = email => document.querySelector('h2 span').textContent = email;
(() =>
{
document.querySelectorAll('li.contact')
.forEach(link =>
{
link.addEventListener('click', () =>
{
theLinkContains(link.querySelector('.preview').textContent);
});
});
})();
ul {
display: flex;
flex-direction: column;
padding-left: 0;
margin-bottom: 0;
}
li {
position: relative;
display: block;
padding-left: 5px;
margin-bottom: -1px;
background-color: rgb(255, 255, 255);
border: 1px solid rgba(0, 0, 0, .125);
}
.preview {
display: none;
}
<h2>Result: <span></span></h2>
<ul>
<li class="contact">
<div class="wrap">
<span class="contact-status online"></span>
<img src="" alt="" width="45px" height="45px" />
<div class="meta">
<p class="name">John</p>
<p class="preview">john#gmail.com</p>
</div>
</div>
</li>
<li class="contact">
<div class="wrap">
<span class="contact-status online"></span>
<img src="" alt="" width="45px" height="45px" />
<div class="meta">
<p class="name">Bob</p>
<p class="preview">Bob#gmail.com</p>
</div>
</div>
</li>
</ul>

The issue in your code is using .val() which is wrong to have it here, what you need is to select the <li> tag and then perform .find() to get the child .preview and then get its text using .text()
This is what you should have in your code:
$('li.contact').on("click", function(e) {
e.preventDefault();
var data = $(this).find('.preview').text();
console.log(data);
})
<li class="contact">
<div class="wrap">
<span class="contact-status online"></span>
<img src="" alt="" width="45px" height="45px" />
<div class="meta">
<p class="name">John</p>
<p class="preview">john#gmail.com</p>
</div>
</div>
</li>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>

Related

Load More Button with jQuery

I recently approached to javascript and jQuery; I would like to create a load more button for the image grid on my website, the grid have 4 column and right now 16 images with a hover overlay effect and with a tag . I tried to follow many tutorials, I can't find and understand the mistake I made.
The code has been corrected in the following anwers
$(function() {
$(".Box-Hidden").slice(0, 8).show();
$("#loadMoreCont").on('click', function(e) {
e.preventDefault();
$(".Box-Hidden:hidden").slice(0, 2).slideDown();
if ($(".Box-Hidden:hidden").length == 0) {
$("#load").fadeOut('slow');
}
$('html,body').animate({
scrollTop: $(this).offset().top
}, 1500);
});
});
.GridContent {
width: 100%;
height: auto;
}
.Portfolio {
width: 95%;
height: auto;
margin: auto;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: auto;
grid-gap: 5px;
padding-top: 4%;
}
.Box-Hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="GridContent">
<div class="Portfolio">
<!-----image 1 ------>
<div class="Box-Hidden">
<a href="#" class="SpanProp1">
<div class="GridItemsCont">
<img src="#" class="gridimg">
<div class="infos infocolor1">
<p>logo</p>
<button>Learn More</button>
</div>
</div>
</a>
</div>
<!-----image 2 ------>
<div class="Box-Hidden">
<a href="#" class="SpanProp2 ">
<div class="GridItemsCont">
<img src="#">
<div class="infos infocolor2">
<p>logo</p>
<button>Learn More</button>
</div>
</div>
</a>
</div>
<!-----total 16 images----->
</div>
</div>
<div class="loadMoreCont">
Load More
<img class="loadImg" src="images/arrow.png">
</div>
Some issues in your code are that the classes and ID's are mixed up in the JS. In particular the loadMore button and how many items you're choosing to show via "slice". It would also help to use a more general or "semantic" friendly name for your containers instead of Box-Hidden because it's not always hidden and it's purpose is more like a card block, so naming it something like "card" might be best. The example below shows the Load More button and then disappears after displaying the rest of the cards.
// slice is choosing the first 2 instances of "Box-hidden" and showing them
$(".Box-Hidden").slice(0, 2).show();
// if there are Box-Hidden set to display:none (hidden) then show the loadMore button
if ($(".Box-Hidden:hidden").length != 0) {
$("#loadMore").show();
}
$("#loadMore").on('click', function(e) {
e.preventDefault();
$(".Box-Hidden:hidden").slice(0, 2).slideDown();
// if there are no more hidden Box-Hidden's then hide the loadMore button
if ($(".Box-Hidden:hidden").length == 0) {
$("#loadMore").fadeOut('slow');
}
// This is not related to the show more, this just brings you back up the page
$('html,body').animate({
scrollTop: $(this).offset().top
}, 1500);
});
.GridContent {
width: 100%;
height: auto;
}
.Portfolio {
width: 95%;
height: auto;
margin: auto;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: auto;
grid-gap: 5px;
padding-top: 4%;
}
.Box-Hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="GridContent">
<div class="Portfolio">
<!-----image A ------>
<div class="Box-Hidden" style="display: none;">
<a href="#" class="SpanProp2 ">
<div class="GridItemsCont">
<img src="http://placekitten.com/200/300?image=1">
<div class="infos infocolor2">
<p>logo</p>
<button>Learn More</button>
</div>
</div>
</a>
</div>
<!-----image B ------>
<div class="Box-Hidden" style="display: none;">
<a href="#" class="SpanProp2 ">
<div class="GridItemsCont">
<img src="http://placekitten.com/200/300?image=2">
<div class="infos infocolor2">
<p>logo</p>
<button>Learn More</button>
</div>
</div>
</a>
</div>
<!-----image 1 ------>
<div class="Box-Hidden" style="display: none;">
<a href="#" class="SpanProp1">
<div class="GridItemsCont">
<img src="http://placekitten.com/200/300?image=3" class="gridimg">
<div class="infos infocolor1">
<p>logo</p>
<button>Learn More</button>
</div>
</div>
</a>
</div>
<!-----image 2 ------>
<div class="Box-Hidden" style="display: none;">
<a href="#" class="SpanProp2 ">
<div class="GridItemsCont">
<img src="http://placekitten.com/200/300?image=4">
<div class="infos infocolor2">
<p>logo</p>
<button>Learn More</button>
</div>
</div>
</a>
</div>
<!-----total 16 images----->
</div>
</div>
<div class="loadMoreCont">
Load More
<img class="loadImg" src="images/arrow.png">
</div>
When you use
$("#loadMoreCont").on(...)
it is supposed you have a html tag having the id with that name:
<div id="loadMoreCont">
...
</div>
When you use
$(".loadMoreCont").on(...)
it is supposed you have a html tag having the class with that name:
<div class="loadMoreCont">
...
</div>
Update
$(function () {
$(".Box-Hidden").slice (0, 2).show(); // showing 2 initial images
$(".loadMoreCont").on('click', function (e) {
e.preventDefault();
$(".Box-Hidden:hidden").slice(0,2).slideDown(); // adding 2 images on load more click
if ($(".Box-Hidden:hidden"). length == 0){
$("#load").fadeOut ('slow');
}
$('html,body').animate({
scrollTop: $(this).offset().top
}, 1500);
});
});
Your code seems work fine. I commented out some interesting lines.
Hope this helps.
your #loadMoreCont JS file on line 4 is targeted at an ID (#).
but on your html loadMoreCont as a class (.)
The question is: " I would like to create a load more button for the image grid on my website, the grid have 4 column and right now 16 images with a hover overlay effect and with a tag . I tried to follow many tutorials, I can't find and understand the mistake I made"
Here the updated code after the kind correction of the users #Kurohige and #WkL
HTML
<div class="GridContent">
<div class="Portfolio">
<!-----image 1 ------>
<div class="Box-Hidden">
<a href="#" class="SpanProp1">
<div class="GridItemsCont">
<img src="#" class="gridimg">
<div class="infos infocolor1">
<p>logo</p>
<button>Learn More</button>
</div>
</div>
</a>
</div>
<!-----image 2 ------>
<div class="Box-Hidden">
<a href="#" class="SpanProp2 ">
<div class="GridItemsCont">
<img src="#">
<div class="infos infocolor2">
<p>logo</p>
<button>Learn More</button>
</div>
</div>
</a>
</div>
<!-----total 16 images----->
</div>
</div>
<div class="loadMoreCont">
Load More
<img class="loadImg" src="images/arrow.png">
</div>`
CSS
.GridContent {
width: 100%;
height: auto;
}
.Portfolio {
width: 95%;
height: auto;
margin: auto;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: auto;
grid-gap: 5px;
padding-top: 4%;
}
.Box-Hidden {
display: none;
}
JQUERY
<script>
$(function () {
$(".Box-Hidden").slice (0, 8).show();
$(".loadMoreCont").on('click', function (e) {
e.preventDefault();
$(".Box-Hidden:hidden"). slice(0,2).slideDown();
if ($(".Box-Hidden:hidden"). length == 0){
$("#load").fadeOut ('slow');
}
$('html,body').animate({
scrollTop: $(this).offset().top
}, 1500);
});
});
</script>
<script src="jQuery/jquery-3.4.1.js"></script>

How to get link from an element and add to all elements of parent element using JavaScript

I have many divs with a class and every div contains diferent elements including a link.
what I want is to get the link and add it to all Elments of parent div such as img, headline etc. (using JavaScript)
Ex:
.myClass{
background-color:red;
display:inline-block;
width:150px;
overflow:hidden;
}
<div class="myClass">
<div></div>
<div></div>
<div><h1>test</h1></div>
<div><img src="https://scx1.b-cdn.net/csz/news/800/2019/2-nature.jpg" alt="">
Link1
</div>
</div>
<div class="myClass">
<div></div>
<div></div>
<div><h1>test</h1></div>
<div><img src="https://scx1.b-cdn.net/csz/news/800/2019/2-nature.jpg" alt="">
Link2
</div>
</div>
This is the fastest
Note I use function where I want to get at this or $(this)
$(function() { // on page load
$(".ecs-event").on("click", function() { // click any ecs-event container
location = $(this).find("a[rel=bookmark]").attr("href"); // find the bookmark
})
});
.myClass {
background-color: red;
display: inline-block;
width: 150px;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ecs-events compact compact-1">
<div class="ecs-event maerz_ecs_category">
<div class="date_thumb">
<div class="month">Mar</div>
<div class="day">6</div>
</div>
<div class="ecs-thumbnail"><img width="75" height="75" src="https://dev.musikzentrum-hannover.de/wp-content/uploads/2019/12/01-03-hannover-schulparty-1-200x200.jpg" class="attachment-75x75 size-75x75 wp-post-image" alt=""></div>
<div class="summary">Hannover Schulparty – abgesagt!</div>
<div class="ecs-button">Mehr erfahren</div>
</div>
<div class="ecs-event maerz_ecs_category">
<div class="date_thumb">
<div class="month">Mar</div>
<div class="day">7</div>
</div>
<div class="ecs-thumbnail"><img width="75" height="75" src="https://dev.musikzentrum-hannover.de/wp-content/uploads/2019/10/001-200x200.jpg" class="attachment-75x75 size-75x75 wp-post-image" alt=""></div>
<div class="summary">Eno und Sero el Mero – abgesagt</div>
<div class="ecs-button">Mehr erfahren</div>
</div>
</div>
Plain JS
window.addEventListener("load", () => { // on page load
[...document.querySelectorAll(".ecs-event")].forEach(div => { // find all ecs-event
div.addEventListener("click", function(e) { // add a click handler
location = this.querySelector("a[rel=bookmark]").getAttribute("href"); // find the bookmark
})
})
});
.myClass {
background-color: red;
display: inline-block;
width: 150px;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ecs-events compact compact-1">
<div class="ecs-event maerz_ecs_category">
<div class="date_thumb">
<div class="month">Mar</div>
<div class="day">6</div>
</div>
<div class="ecs-thumbnail"><img width="75" height="75" src="https://dev.musikzentrum-hannover.de/wp-content/uploads/2019/12/01-03-hannover-schulparty-1-200x200.jpg" class="attachment-75x75 size-75x75 wp-post-image" alt=""></div>
<div class="summary">Hannover Schulparty – abgesagt!</div>
<div class="ecs-button">Mehr erfahren</div>
</div>
<div class="ecs-event maerz_ecs_category">
<div class="date_thumb">
<div class="month">Mar</div>
<div class="day">7</div>
</div>
<div class="ecs-thumbnail"><img width="75" height="75" src="https://dev.musikzentrum-hannover.de/wp-content/uploads/2019/10/001-200x200.jpg" class="attachment-75x75 size-75x75 wp-post-image" alt=""></div>
<div class="summary">Eno und Sero el Mero – abgesagt</div>
<div class="ecs-button">Mehr erfahren</div>
</div>
</div>

Prevent auto search / add a search button List.js

This should be a straightforward problem but I haven't found the solution anywhere on the list.js documentation. How do I go about preventing the list from auto searching as I type in the search field and instead add a search button instead?
var options = {
valueNames: ['material', 'type', 'thickness', 'height', 'category']
};
var featureList = new List('piece-search', options);
.item {
margin: 0.5em;
padding: 0.5em;
width: 150px;
height: 150px;
float: left;
background: #229B55;
color: #F4F4F4;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
}
.item p {
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="page">
<div id="main">
<div class="c1">
<div id="piece-search">
<ul class="sort-by">
<li>
<input class="search" placeholder="Search pieces">
</li>
</ul>
<ul class="list">
<li class="item">
<p class="sorting-info hide-this">
<p class="material">plastic</p>
<p class="type">pipe</p>
<p class="thickness">3mm</p>
<p class="height">15inch+</p>
<p class="category">artsy</p>
</li>
<li class="item">
<p class="sorting-info hide-this">
<p class="material">glass</p>
<p class="type">pipe</p>
<p class="thickness">5mm</p>
<p class="height">14inch-</p>
<p class="category">scientific</p>
</li>
</ul>
</div>
</div>
</div>
</div>
The default class for search is "search" according to the documentation. So, you need to remove/change the classname from text input box in order to prevent auto search onkeyup.
I added a button for search that will call the function search() where you will get the search text value and search manually.
To search manually, read the documentation provided here.
JS function that will trigger on button click:
function search() {
var searchText = document.getElementById("searchText").value;
//console.log(searchText);
var options = {
valueNames: ['material', 'type', 'thickness', 'height', 'category']
};
var featureList = new List('piece-search', options);
// Search manually
featureList.search(searchText);
// Search manually on specific columns
//listObj.search(searchText, [ 'material' ]);
}
function search() {
var searchText = document.getElementById("searchText").value;
//console.log(searchText);
var options = {
valueNames: ['material', 'type', 'thickness', 'height', 'category']
};
var featureList = new List('piece-search', options);
// Search manually
featureList.search(searchText);
// Search manually on specific columns
//listObj.search(searchText, [ 'material' ]);
}
.item {
margin: 0.5em;
padding: 0.5em;
width: 150px;
height: 150px;
float: left;
background: #229B55;
color: #F4F4F4;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
}
.item p {
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="page">
<div id="main">
<div class="c1">
<div id="piece-search">
<ul class="sort-by">
<li>
<input id="searchText" placeholder="Type text to search">
</li>
<li>
<input type="button" class="searchButton" value="Search pieces" onclick="search()">
</li>
</ul>
<ul class="list">
<li class="item">
<p class="sorting-info hide-this">
<p class="material">plastic</p>
<p class="type">pipe</p>
<p class="thickness">3mm</p>
<p class="height">15inch+</p>
<p class="category">artsy</p>
</li>
<li class="item">
<p class="sorting-info hide-this">
<p class="material">glass</p>
<p class="type">pipe</p>
<p class="thickness">5mm</p>
<p class="height">14inch-</p>
<p class="category">scientific</p>
</li>
</ul>
</div>
</div>
</div>
</div>

How to show div when hovering dynamically a link?

I have different a-tags which gets generated dynamically. Each link will generate an own div with different contents so each div has an individual content as well as an individual height.
Now I would like to achieve that when hovering an a the matching div will be shown. The div then should be shown at the mouse position and should be position from bottom to top direction so that the div is "growing in upward direction" because the links are on the bottomside of the page.
Here is what the code is look like ($z is a counter):
<a href="<?php echo $link_djv;?>" class="rsshover" id="djvl_<?php echo $z;?>" target="_blank">
<li>
<p class="headline"><?php echo $title_djv;?></p>
</li>
</a>
<div class="preview" id="djvd_<?php echo $z;?>">
<?php echo $description_djv;?>
</div>
I read already through different threads but wasn't able to find a proper way on how to solve this issue. Thanks in advance.
Run Snippet
This is a basic version of what you need. obviously the animation needs work but should give you a good starting point.
class ToolTipControl {
constructor () {
this.xCoordinate;
this.yCoordinate;
this.links = document.querySelectorAll('a');
this.addEventListeners();
this.activeLink = false;
}
addEventListeners () {
for (let link of this.links) {
link.addEventListener('mouseenter', (e) => this.handleMouseEnter(e));
link.addEventListener('mouseleave', (e) => this.handleMouseLeave(e));
}
document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
}
handleMouseMove (event) {
this.xCoordinate = event.pageX;
this.yCoordinate = event.pageY;
if (this.activeLink) {
this.activeLink.style.top = `${this.yCoordinate}px`;
this.activeLink.style.left = `${this.xCoordinate}px`;
}
}
handleMouseEnter (event) {
this.activeLink = event.target.nextElementSibling;
this.activeLink.style.maxHeight = '50px';
}
handleMouseLeave (event) {
let targetsContent = event.target.nextElementSibling;
targetsContent.style.maxHeight = 0;
this.activeLink = false;
}
}
new ToolTipControl();
.preview {
position: absolute;
max-height: 0;
overflow: hidden;
transition: max-height 0.6s ease;
}
li {
list-style: none;
}
a {
padding: 20px;
margin: 20px;
color: white;
display: block;
background-color: grey;
width: 100px;
}
<a href="/" class="rsshover" id="djvl_123" target="_blank">
<li>
<p class="headline">some title</p>
</li>
</a>
<div class="preview" id="djvd_098">
content 1
</div>
<a href="/" class="rsshover" id="djvl_123" target="_blank">
<li>
<p class="headline">some title</p>
</li>
</a>
<div class="preview" id="djvd_098">
content 2
</div>
<a href="/" class="rsshover" id="djvl_123" target="_blank">
<li>
<p class="headline">some title</p>
</li>
</a>
<div class="preview" id="djvd_098">
content 3
</div>
You're going to need to add a mouse over event of your link and then a javascript function to show your div in the right location. Then you'll need a mouseout even to hide the div again.
what I would start with is change your php code to be:
<a href="<?php echo $link_djv;?>" class="rsshover" onmouseover="showDiv('<?php echo $z;?>');" onmouseout="hideDiv('<?php echo $z;?>');" id="djvl_<?php echo $z;?>" target="_blank">
<li>
<p class="headline"><?php echo $title_djv;?></p>
</li>
</a>
<div class="preview" id="djvd_<?php echo $z;?>" style="display:none;">
<?php echo $description_djv;?>
</div>
Then add a javascript function:
<script>
function showDiv(counter) {
document.getElementById('djvd_' + counter).style.display = 'block';
// this is where you'd position your div location
}
function hideDiv(counter) {
document.getElementById('djvd_' + counter).style.display = 'none';
}
</script>
You can use CSS by putting the div.preview inside the a.rsshover
.rsshover .preview {
display: none;
}
.rsshover:hover .preview {
display: block;
}
<a href="#" class="rsshover" target="_blank">
<li>
<p class="headline">1</p>
</li>
<div class="preview">
ONE
</div>
</a>
<a href="#" class="rsshover" target="_blank">
<li>
<p class="headline">2</p>
</li>
<div class="preview">
TWO
</div>
</a>
<a href="#" class="rsshover" target="_blank">
<li>
<p class="headline">3</p>
</li>
<div class="preview">
THREE
</div>
</a>
I don't understand how exactly do you want your preview to be displayed, but this should help you.
(function($) {
var $currentElement;
$('.rsshover').on('mouseenter', function(e) {
$currentElement = $('#djvd_' + $(this).attr('id').substr(5));
$currentElement.css({
position: 'absolute',
display: 'block',
top: e.clientY + 'px',
left: e.clientX + 'px'
});
}).on('mouseleave', function() {
$currentElement.hide()
})
})(jQuery)
.preview {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="rsshover" id="djvl_1" target="_blank">
<li>
<p class="headline">Headline</p>
</li>
</a>
<div class="preview" id="djvd_1">
Description 1
</div>
Also, please don't put <li> tags inside anchor <a>.

Hide a div that is currently opened and show the div thats clicked,and vice versa

I basically want to create a product listing page using jquery, just like this page: https://losangeles.sharegrid.com/browse/
Here is my code:
$(function(){
$('.link').click(function(){
$(this).next('ul').toggle();
var id = $(this).attr("rel");
$('#'+id).show();
});
});
.container {
width: 100%;
height: auto;
}
.eighty-percent {
width: 80%;
margin: 0 auto;
}
.categories {
width: 20%;
float: left;
ul {
li {
ul {
display: none;
}
}
}
}
.products-list {
width: 80%;
float: right;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="eighty-percent">
<div class="categories left">
<ul>
<li>
<a href="#" class="link" id="main-category" rel="main1">
main-category-one
</a>
<ul>
<li>sub-cat-one</li>
<li>sub-cat-one</li>
<li>sub-cat-one</li>
<li>sub-cat-one</li>
</ul>
</li>
</ul>
</div>
<div class="products right">
<div class="products-list" id="main1">
<h1>main category one</h1>
</div>
<div class="products-list" id="main-sub1">
<h1>sub category one</h1>
</div>
<div class="products-list" id="main-sub2">
<h1>sub category one</h1>
</div>
<div class="products-list" id="main-sub3">
<h1>sub category one</h1>
</div>
<div class="products-list" id="main-sub4">
<h1>sub category one</h1>
</div>
</div>
</div>
</div>
Now the problem I am having is as you can see, I cannot make the div that is currently opened make hidden when I click on the other sub category links. I hope my snippet will make clear what I am trying to achieve
All changes and details are commented within the source.
FIDDLE
SNIPPET
$(function() {
$('.link').click(function(event) {
/*
Added to prevent <a>nchor links
from jumping. Note the `event`
parameter above as well.
*/
event.preventDefault();
$(this).next('ul').toggle();
var id = $(this).attr("rel");
/*
Added a class (i.e. `sub`), to
each #main-sub* so all of them will
be targeted to hide by the .hide()
method.
*/
$('.sub').hide();
$('#' + id).show();
});
});
.container {
width: 100%;
height: auto;
}
/*
Added to prevent the right
column from wrapping under
the left column.
*/
.subList {
height: 100vw;
display: none;
}
.categories {
width: 50%;
float: left;
}
.products-list {
width: 50%;
float: right;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<!--Removed .eighty-percent because it
hindered layout in demo only,
adding it or removing it shouln't
affect functionality in your production version.-->
<div class="categories left">
<ul>
<li>
main-category-one
<!--Added a class (i.e. subList)
in order to style it easier,
see CSS for why styling was needed -->
<ul class="subList">
<!--Changed each <a>nchor id as a
unique one. You should never have more
than one of the same id on a page.-->
<li>sub-cat-one
</li>
<li>sub-cat-two
</li>
<li>sub-cat-three
</li>
<li>sub-cat-four
</li>
</ul>
</li>
</ul>
</div>
<div class="products right">
<div class="products-list" id="main1">
<h1>main category one</h1>
</div>
<div class="products-list sub" id="main-sub1">
<h2>sub category one</h2>
</div>
<div class="products-list sub" id="main-sub2">
<h2>sub category two</h2>
</div>
<div class="products-list sub" id="main-sub3">
<h2>sub category three</h2>
</div>
<div class="products-list sub" id="main-sub4">
<h2>sub category four</h2>
</div>
</div>
</div>
As far as I understood, you want to hide the main div when another was clicked.
This would achieve it:
$(function() {
$('.link').click(function() {
$(this).next('ul').toggle();
var id = $(this).attr("rel");
$('div[id^="main"]').hide(); // added line
$('#' + id).show();
});
});

Categories

Resources