Check link click happen within a div - javascript

I would like the Javascript returning true when users click on the links within specific div
For example:
When users click on links in div having class="span1", it will return true
<div class="span1">
<h3>Title 3</h3>
<ul class="stages" dir="ltr">
<li><a href="http://www.example.com" >Example 1</a></li>
<li><a href="http://www.example.com" >Example 2</a></li>
</ul>
</div>
<div class="span2">
<h3>Title 4</h3>
<ul class="stages" dir="ltr">
<li><a href="http://www.example.com" >Example 1</a></li>
<li><a href="http://www.example.com" >Example 2</a></li>
</ul>
</div>
Thanks a lot!!

Simply use an if statement for .hasClass:
$("div").click(function(){
if($(this).hasClass("span1")){
alert("SPAN 1 CLICKED");
return true;
}
});
FIDDLE
UPDATE: I read your question too quick, here is a new fiddle which targets your a's instead of the div
NEW FIDDLE
should be this instead:
if($(this).closest("div").hasClass("span1")){

Here in pure Javascript: http://jsfiddle.net/xxx96bta/5/
var links = document.getElementsByTagName('a'); //collect your elements
for (i = 0; i < links.length; i++) {
(function () {
links[i].addEventListener('click', whatSpan, false);
})();
}
function whatSpan() {
var parentspan = this.parentNode.parentNode.parentNode.className;
if (parentspan == "span1") {
alert("you clicked span 1");
} else {
alert("you clicked span 2");
}
}

Related

How to change colour of an element nested in other elements using javascript

I have a list structured as such:
<ul class="list">
<li class="list-element ">
<a href="#"><a>
</li>
</ul>
<button onclick="changeColour()"></button>
<script src="js/index.js"></script>
The css for my links are:
ul li a {
color: red
{
How do I change the colour of my links?? I know you can do this:
function changeColour() {
var div = document.getElementsByTagName("ul");
div.style.changeColour = "rgb(0, 212, 177)";
}
but I don't know how to the links within list item within the list.
Try document.querySelectorAll:
let links = document.querySelectorAll("ul.list li.list-element a");
for (let link of links) {
link.style.color = "rgb(0, 212, 177)";
}
ul li a {
color: red
{
<ul class="list">
<li class="list-element">
LINK 1
</li>
<li class="list-element">
LINK 2
</li>
</ul>
You can change it with css. Your css is correct but you missed ; after red. And you can do it with javascript too or you can use both if you want to give it a color then change it at run time. For your javascript code you forgot to add the collection's index...
document.getElementsByTagName('a')[0].style.color='orange';
NB: I'm targeting the first anchor with [0]. To target all anchors loop through the collection.
Like this
function changeColour() {
var div = document.getElementsByTagName("a");
for(var i = 0; i < div.length; i++){
div[i].style.color = "rgb(111, 112, 112)";
}
}
changeColour();
ul li a {
color: red;
{
<ul class="list">
<li class="list-element ">
<a href="#">link 1<a>
</li>
<li class="list-element ">
<a href="#">link 2<a>
</li>
</ul>
HTML
<ul class="list">
<li class="list-element ">
<a href="#">link 1<a>
</li>
<li class="list-element ">
<a href="#">link 2<a>
</li>
</ul>
Script
$('.list').each(function(){
$(this).find('li a').css('color','rgb(111, 112, 112)');
});
Below is Jquery model in case you are looking for it
// Jquery model if you want to use
$(document).ready(function(){
$('#change').click(function(){
var color=["blue","red","yellow","black","pink","green"];
var prompts = prompt("please type your valid color");
// checking if entered colored is registered
for(x in color){
if(color[x] ==prompts){
//registered then set its value as color
$("a").css({"color":prompts});
return ;
}
}
// deal with unregistered color
var conf = confirm('not registered color entered , do you want to set the default color?');
if(conf ==true ){
$("a").css({"color":"black"});
}
});
});
ul li a {
color: red;
{
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
<li class="list-element ">
link 1
</li>
<li class="list-element ">
link 2
</li>
</ul>
<p id='change'> please click here to change link color </p>

How to set the nav ul display to none when clicked second time on the hamburger?

I am developing a responsive website in which when clicked on hamburger, displays a nav ul, but I have not been able to set the list display to none when clicked on the hamburger second time.
HTML
<div class=""container hamburger" onclick="toggleHamburger(this)" id="hamburger">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
<ul class="col-m-9 navlist" id="navlist">
<li><a id="HTML" href="#">HTML</a></li>
<li><a id="CSS" href="#">CSS</a></li>
<li><a id="JS" href="#">JS</a></li>
<li><a id="FAQ" href="#">FAQ</a></li>
<li><a id="About" href="#">About</a></li>
JS
function toggleHamburger(hamburg) {
hamburg.classList.toggle("change");
displayNavList();
}
function displayNavList(){
var navList = document.getElementById("navlist");
navList.style.display = "block";
}
So, basically I want to know that if there is any way in JS to call another function when clicked on the hamburger second time.
See the problem on AdiCodes, with the hamburger, it can open the nav list but cannot close it.
Is that what you want to achieve ? or did I misunderstand the question ?
var hamburger = document.querySelector('#hamburger'),
navList = document.querySelector('#navlist');
var toggleNav = function() {
hamburger.classList.toggle('js-active')
navList.classList.toggle('js-active')
}
hamburger.addEventListener('click', toggleNav)
#hamburger {
color: red;
}
.js-active#hamburger {
color: green;
}
#navlist {
display: none;
}
.js-active#navlist {
display: block;
}
<div class="container hamburger" id="hamburger">
HAMBURGER
</div>
<ul class="col-m-9 navlist" id="navlist">
<li><a id="HTML" href="#">HTML</a></li>
<li><a id="CSS" href="#">CSS</a></li>
<li><a id="JS" href="#">JS</a></li>
<li><a id="FAQ" href="#">FAQ</a></li>
<li><a id="About" href="#">About</a></li>
</ul>
Why don't you show/hide your list with a class, then you can toggle that class in your click handler too:
function toggleHamburger(hamburg) {
hamburg.classList.toggle("change");
var navList = document.getElementById("navlist");
navList.classList.toggle("shown");
}
With the CSS:
#navlist:not(.shown) {
display: none;
}
You can define a global counter
var count = 0;
The first time you click it will show your nav, and the second time it will toggle.
var count = 0;
function toggleHamburger(hamburg) {
if(count >= 1){
var navList = document.getElementById("navlist");
navList.style.display = "none";
}else{
hamburg.classList.toggle("change");
displayNavList();
}
count ++;
}
function displayNavList(){
var navList = document.getElementById("navlist");
navList.style.display = "block";
}
<div class="container hamburger" onclick="toggleHamburger(this)" id="hamburger">
<div class="bar1">test</div>
<div class="bar2">test</div>
<div class="bar3">test</div>
</div>
<ul class="col-m-9 navlist" id="navlist" style="display: none;">
<li><a id="HTML" href="#">HTML</a></li>
<li><a id="CSS" href="#">CSS</a></li>
<li><a id="JS" href="#">JS</a></li>
<li><a id="FAQ" href="#">FAQ</a></li>
<li><a id="About" href="#">About</a></li>

jQuery set class active with anchor

I have a menu like :
<ul>
<li>
<a class="scroll-to" href="#one">one</a>
</li>
<li>
<a class="scroll-to" href="#two">two</a>
</li>
<li>
<a class="scroll-to" href="#three">three</a>
</li>
</ul>
And on my page, multiple anchor like :
<a id="two" target="_blank"></a>
or
<a id="one" target="_blank"></a>
I'm looking for a way to set an active class to my menu when i scroll to an anchor (with click or mouse scroll).
For example if i scroll to my anchor id="two" i need to set active my li #two.
Any ideas ?
If I understand your problem, add your anchors some class, for example section and try this:
$('.section').hover(function() {
var anchor = $(this).attr('id');
$('a[href="#'+anchor+'"]').addClass('active');
}, function() {
$('a').removeClass('active');
});
http://codepen.io/tomekbuszewski/pen/MwMWoK
var links = document.querySelectorAll("a.scroll-to");
console.log(links[1]);
for (var i = links.length -1; i>=0; i--)
{
//click event
links[i].onclick= someHandlerFunction;
//hover event
links[i].onmouseover= someHandlerFunction;
}
var liActive = undefined;
function someHandlerFunction(event) {
if (liActive != undefined) liActive.setAttribute("class", "");
liActive = event.target.parentNode;
liActive.setAttribute("class", "active");
return false;
}
.menu{
background-color: #00ff00;
}
.menu li.active{
background-color: blue;
}
<ul class="menu">
<li>
<a class="scroll-to" href="#one">one</a>
</li>
<li>
<a class="scroll-to" href="#two">two</a>
</li>
<li>
<a class="scroll-to" href="#three">three</a>
</li>
</ul>
Voila (add and remove class in the same time), it's a but it's a bit redundant to add active class at click and hover.

Unable to highlight the first element of a menu list

I have a List of menu as below:
<ul id="tablist">
<li><a class="tab" href="#" onclick="return expandcontent('sc1', this)">Menu1</a></li>
<li><a class="tab" href="#" onclick="return expandcontent('sc2', this)">Menu2</a></li>
<li><a class="tab" href="#" onclick="return expandcontent('sc3', this)">Menu3</a></li>
<li><a class="tab" href="#" onclick="return expandcontent('sc4', this)">Menu4</a></li>
<li><a class="tab" href="#" onclick="return expandcontent('sc5', this)">Menu5</a></li>
</ul>
On click the menu item it will show div sc1,sc2,sc3,sc4,sc5 resp. The javascript I have used is below:
var initialtab=[1, "sc1"]
function cascadedstyle(el, cssproperty, csspropertyNS) {
if (el.currentStyle)
return el.currentStyle[cssproperty]
else if (window.getComputedStyle) {
var elstyle=window.getComputedStyle(el, "")
return elstyle.getPropertyValue(csspropertyNS)
}
}
var previoustab=""
function expandcontent(cid, aobject) {
var links=document.getElementsByTagName("a");
for(i=0;i<links.length;i++) {
if(links[i].className=="tab") {
links[i].style.fontWeight="normal";
}
}
aobject.style.fontWeight="bold";
if (document.getElementById) {
highlighttab(aobject)
detectSourceindex(aobject)
if (previoustab!="")
document.getElementById(previoustab).style.display="none"
document.getElementById(cid).style.display="block"
previoustab=cid
if (aobject.blur)
aobject.blur()
return false
} else
return true
}
function highlighttab(aobject) {
if (typeof tabobjlinks=="undefined")
collecttablinks()
}
function collecttablinks() {
var tabobj=document.getElementById("tablist")
tabobjlinks=tabobj.getElementsByTagName("A")
}
function detectSourceindex(aobject) {
for (i=0; i<tabobjlinks.length; i++) {
if (aobject==tabobjlinks[i]) {
tabsourceindex=i
}
}
}
function do_onload() {
var cookiename=(typeof persisttype!="undefined" && persisttype=="sitewide")? "tabcontent" : window.location.pathname
var cookiecheck=window.get_cookie && get_cookie(cookiename).indexOf("|")!=-1
collecttablinks()
initTabcolor=cascadedstyle(tabobjlinks[1], "fontWeight", "fontWeight")
initTabpostcolor=cascadedstyle(tabobjlinks[0], "fontWeight", "fontWeight")
if (typeof enablepersistence!="undefined" && enablepersistence && cookiecheck) {
var cookieparse=get_cookie(cookiename).split("|")
var whichtab=cookieparse[0]
var tabcontentid=cookieparse[1]
expandcontent(tabcontentid, tabobjlinks[whichtab])
} else
expandcontent(initialtab[1], tabobjlinks[initialtab[0]-1])
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload
</script>
The divs are as follows:
<div id="tabcontentcontainer">
<div id="sc1" class="tabcontent">
<span style="font-size:9pt; color:black;">Content 1 goes here</span>
</div>
<div id="sc2" class="tabcontent">
<img src="images/image.png"/>
</div>
<div id="sc3" class="tabcontent">
<span style="font-size:9pt; color:black;">Content 3 goes here</span>
</div>
<div id="sc4" class="tabcontent">
<span style="font-size:9pt; color:black;">Content 4 goes here</span>
</div>
<div id="sc5" class="tabcontent">
<span style="font-size:9pt; color:black;">Content 5 goes here</span>
</div>
My problem is I am unable to highlight the first menuitem as bold when the page loads i.e. the I want to highlight Menu1 as default selected item when the page loads. Please help out.
Thanks in advance.
using CSS
#tablist li:first-child {
background-color: #0094ff;
}
This is what you want to use:
ul li:first-child {
font-weight:bold;
}
jsFiddle
The solution to this is quite easy and the JS error would certainly come up if you checked your console. You're missing IDs of your LI elements, so you can't make the first LI bold by using getElementById().
Here's an updated HTML code that will work:
<ul id="tablist">
<li><a class="tab" id="sc1" href="#" onclick="return expandcontent('sc1', this)">Menu1</a></li>
<li><a class="tab" id="sc2" href="#" onclick="return expandcontent('sc2', this)">Menu2</a></li>
<li><a class="tab" id="sc3" href="#" onclick="return expandcontent('sc3', this)">Menu3</a></li>
<li><a class="tab" id="sc4" href="#" onclick="return expandcontent('sc4', this)">Menu4</a></li>
<li><a class="tab" id="sc5" href="#" onclick="return expandcontent('sc5', this)">Menu5</a></li>
</ul>
A working JSFiddle: http://jsfiddle.net/TSHVP/
Depending on which browsers you're targetting, you might even go with a CSS selector, which would be quicker than using JavaScript on window load (see other answers).
If you allowed to use JQuery:
$(document).ready(function() {
$('#tablist>li').first().css( "font-weight", "bold" );
})
You can use below code to achieve this,
$("#tablist li:first").css('font-weight','bold');
Check Demo
I am using jquery version1.9.1

Traverse from one UL to another UL with .next

I have got myself stuck on something which seems possible, I just havent been able to figure it out for 2 days!
I have this in my .js file:
Mousetrap.bind('right', function() { $('li.active').next().click(); });
Mousetrap.bind('left', function() { $('li.active').prev().click(); });
Above is binding the keyboard right/left to move through all LI in a UL on keypress .
I then have this in my HTML; which is two UL's.
At the moment, when I hit the last item in the first UL, it stops. I am trying to get it to jump to the next LI in the following UL.
I have tried to figure out how to use nextAll() - Multiple list traversal but to no avail, anyone have any ideas?
<div class="item active">
<ul class="thumbnails">
<li class="trigger active" data-target="0" data-fieldclass="data1">
<p class="image"><img src="images/sias-duplessis.jpg" alt="Sias Du Plessis"></p>
<p>#siasduplessis</p>
<p>#RedFury</p>
</li>
<li class="trigger" data-target="1" data-fieldclass="data2">
<p class="image"><img src="images/lance-witten.jpg" alt="Lance Witten"></p>
<p>#LanceTheWitten</p>
<p>#pegasus</p>
</li>
<li class="trigger" data-target="2" data-fieldclass="data3">
<p class="image"><img src="images/sasha.jpg" alt="Sasha Martinengo"></p>
<p>#F1sasha</p>
<p>#BallztotheWallz</p>
</li>
<li class="trigger" data-target="3" data-fieldclass="data4">
<p class="image"><img src="images/sipho.jpg" alt="Comrade Sipho"></p>
<p>#comradesipho</p>
<p>#badexample</p>
</li>
<li class="trigger" data-target="4" data-fieldclass="data5">
<p class="image"><img src="images/carl-wastie.jpg" alt="Carl Wastie"></p>
<p>#carlwastie</p>
<p>#FrickinHORSome</p>
</li>
</ul>
</div>
<div class="item">
<ul class="thumbnails">
<li class="trigger" data-target="5" data-fieldclass="data6">
<p class="image"><img src="images/craig-stack.jpg" alt="Craig Stack"></p>
<p>#Craig_Stack</p>
<p>#eldiablo</p>
</li>
<li class="trigger" data-target="6" data-fieldclass="data7">
<p class="image"><img src="images/cale-pisarra.jpg" alt="Cale Pisarra"></p>
<p>#calepissarra</p>
<p>#thedirtyseagull</p>
</li>
<li class="trigger" data-target="7" data-fieldclass="data8">
<p class="image"><img src="images/mr-cpt.jpg" alt="Mr Cape Town"></p>
<p>#MrCPT</p>
<p>#goodoak</p>
</li>
<li class="trigger" data-target="8" data-fieldclass="data9">
<p class="image"><img src="images/life-is-savage.jpg" alt="Life Is Savage"></p>
<p>#LifeisSavage</p>
<p>#whoyourdaddy</p>
</li>
<li class="trigger" data-target="9" data-fieldclass="data10">
<p class="image"><img src="images/brent-graham.jpg" alt="Brent Graham"></p>
<p>#BrentGraham</p>
<p>#thefalcon</p>
</li>
</ul>
You can use this methods
function NextClick()
{
var li = $('ul.thumbnails li.active');
var index = $("ul.thumbnails li").index(li);
$("ul.thumbnails li").eq(index + 1).click();
}
function PrevClick()
{
var li = $('ul.thumbnails li.active');
var index = $("ul.thumbnails li").index(li);
if(index > 0)
$("ul.thumbnails li").eq(index - 1).click();
}
See working example in JsFiddle.
Mousetrap.bind('right', function() { if($('li.active').next().hasClass("trigger"))$('li.active').next().click();
else $('li.active').closest(".item").next().find(".trigger").first().click()
});
Mousetrap.bind('left', function() { if($('li.active').prev().hasClass("trigger"))$('li.active').prev().click();
else $('li.active').closest(".item").prev().find(".trigger").last().click()
});
DEMO
You can try Chuck Norris Code too
How about:
Mousetrap.bind('right', function() {
if ($('li.active').is(':last-child'))
obj = $('li.active').parents('ul').next('ul').find('li').first();
else obj = $('li.active').next();
obj.click();
});
you can refer to "data-target" attribute as your reference.
you might also have a missing ending on your markup.
Mousetrap.bind('right', function() {
new_active_li = $('ul li[data-target^="' + (parseInt($('ul li.active').attr('data-target')) + 1) +'"]');
$('ul li').removeClass('active');
new_active_li.addClass('active');
new_active_li.click();
});
Mousetrap.bind('left', function() {
new_active_li = $('ul li[data-target^="' + (parseInt($('ul li.active').attr('data-target')) - 1) +'"]');
$('ul li').removeClass('active');
new_active_li.addClass('active');
new_active_li.click();
});
just a simple test will do the trick like
var test = $("ul li.last").next().html();
if(test == 'undefined'){
// jump to next list
var nextList = $("li.active").parent().parent().next().find("ul");
}else{
// the normal code
}

Categories