JQuery adding a class - javascript

I want add a class when a <li> element clicked. but it didn't work. Here's JQuery snippet
$(".mama").click(function(){
var arr = ["cat","dog", "mice", "bird"];
alink = $(this).text();
$.each(arr, function(index, value) {
if(alink == value){
$(this).addClass('hi');
}
});
});
And HTML
<ul id="animal">
<li class="mama">cat</li>
<li class="mama">dog</li>
<li class="mama">Mice</li>
</ul>
i also have tried to do it by .map but nothing happen. please give solution and some explain. Thanks

This should work:
$(".mama").click(function(){
var $this = $(this);
var arr = ["cat","dog", "mice", "bird"];
alink = $(this).text();
$.each(arr, function(index, value) {
if(alink == value){
$this.addClass('hi');
}
});
});
because this inside the each is not the DOM element <li>.

You probably just need to do this:
http://jsfiddle.net/reugB/1/
$('.mama').on('click', function(evt) {
evt.preventDefault();
$(this).addClass('hi');
});

Use this to refer to current element which was clicked.
$(".mama").click(function (e) {
e.preventDefault();
$(this).addClass('hi');
});

If you mean add the class hi to the clicked li, just do like below:
$(".mama").click(function(e){
e.preventDefault();
$(".mama").removeClass('hi');
$(this).addClass('hi')
});

.hi { background-color: #f00 !important;}
$('.mama').on('click', function(evt) {
evt.preventDefault();
$(this).addClass('hi');
});

$(".mama").click(function(e){
e.preventDefault();
var arr = ["cat","dog", "mice", "bird"];
var alink = $(this).find("a").text();
$.each(arr, function(index, value) {
if(alink == value){
$(this).addClass('hi');
}
});
});
see reference text and find

Related

How can I detect if a selector clicked?

What is the best way to detect if a jQuery-selector clicked. i mean:
var elem = 'foo'
var action = $(elem ).mouseenter(function(){
$(this).css('background-image',url(elem +'.png'))
});
var elem = 'bar'
//do the same action with new elem
var elem = 'blah'
//do the same action with new elem
the problem is how can i shorten this code to one line:
$('.far').mouseenter(function(){$(this).css('background-image',url(far.png'))});
$('.foooo').mouseenter(function(){$(this).css('background-image',url(foooo.png'))});
$('.bar').mouseenter(function(){$(this).css('background-image',url(bar.png'))});
$('.some').mouseenter(function(){$(this).css('background-image',url(some.png'))});
try making this array
var arr = [ "far", "foooo", "bar", "some" ];
arr.forEach( function( item ){
$('.' + item ).mouseenter(function(){$(this).css('background-image','url('+ item +'.png'))});
//adding the click detection as well
$('.' + item ).click(function(){$(this).css('background-image','url('+ item +'.png'))});
});
$(function() {
$(document).on('mouseenter', 'div[data-background]', function() {
$(this).css({'background' : 'url('+$(this).data('background')+')',});
});
});
div {
width : 500px;
height : 320px;
border : 1px solid #A2A2A2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div data-background="https://cdn.pixabay.com/photo/2017/04/04/14/23/peacock-2201428_960_720.jpg"></div>
<div data-background="https://cdn.pixabay.com/photo/2013/07/12/18/59/peacock-154128_960_720.png"></div>
</body>
</html>
Works only in this situation.
Since you have single class selector,assuming you don't have multiple classes
$('.far','.foooo','.bar','.some').mouseenter(function(){
var selector = $(this).attr('class');
$(this).css('background-image',url(selector+'.png'));
});
You need something like this:
$(".foo").click(function (event) {
$(this).css("color", "red");
});
Again, you need click, not mouseenter. Because mouseenter is just a hover, which you could do with plain css.

How to pick specific li element which is generated dynamically

I couldn't pick a specific li element on click which is generated dynamically. please help.
Jquery
$(document).ready(function()
{
$('#id1').on('click', 'li', function(e)
{
var val = $(this).find('.pick').attr('data-val1');
console.log(val); // returns only first value for every click
});
});
Dynamically created HTML
var x = document.getElementById("id1");
x.innerHTML= x.innerHTML + '<li class="pick" data-val1="'+i+'"></li>' // where i is a incremental counter
HTML
<ul id ="id1">
// li adds here
</ul>
Try this solution: http://jsfiddle.net/nec47v8d/
You can use this JQUERY
$('#id1 li.pick').click(function (e) {
var val = $(this).attr('data-val1');
alert(val)
});
Try
$(document).ready(function() {
$('#id1').on('click', 'li', function(e) {
var val = $(this).attr('data-val1');
snippet.log('clciekd: ' + val); // returns only first value for every click
});
var i = 0;
$('button').click(function() {
$('<li />', {
'data-val1': ++i,
text: i
}).appendTo('#id1');
})
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="id1"></ul>
<button>Add</button>

Show a specific element with specific button

HTML:
<nav id="sales-countries">
<ul>
<li>...1...</li>
<li>...2...</li>
<li>...3...</li>
<li>...4...</li>
<li>...5...</li>
<li>...6...</li>
<li>...7...</li>
</ul>
</nav>
<nav class="sales-location">...1...</nav>
<nav class="sales-location">...2...</nav>
<nav class="sales-location">...3...</nav>
<nav class="sales-location">...4...</nav>
<nav class="sales-location">...5...</nav>
<nav class="sales-location">...6...</nav>
<nav class="sales-location">...7...</nav>
Javascript:
$("nav.sales-location").hide();
$("#sales-countries a:eq(0)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(0)").show();
});
$("#sales-countries a:eq(1)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(1)").show();
});
$("#sales-countries a:eq(2)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(2)").show();
});
$("#sales-countries a:eq(3)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(3)").show();
});
$("#sales-countries a:eq(4)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(4)").show();
});
$("#sales-countries a:eq(5)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(5)").show();
});
$("#sales-countries a:eq(6)").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq(6)").show();
});
I need, that element of specific number - button, show an element of specific number.
JavaScript code above have this property and work well, but it is too long.
How I make this property for (for example) one hundred buttons and elements for showing so that JavaScript code was very short?
Between code paragraphs is different in the two numbers only!
You can do it by a common function for every li click and you can show corresponding div by jquery index()
try this:
$("nav.sales-location").hide();
$("#sales-countries ul li").click(function() {
ind = $(this).index();//get the li index
$("nav.sales-location").hide();// hide all divs
$("nav.sales-location:eq("+ind+")").show(); //show corresponding index div
});
live demo
Reduce it to just:
$("nav.sales-location").hide();
$("#sales-countries a").click(function() {
$("nav.sales-location").hide();
$("nav.sales-location:eq("+$(this).index('#sales-countries a')+")").show();
});
jsFiddle example
You can pass a selector to .index() to specify what collection it's relative to.
since you're just showing the same text as the a that's clicked you can grab the value using .text() and pass it to an empty div called .sales-location
$("#sales-countries a").click(function() {
var results = $(this).text();
$(".sales-location").html(results);
});
JSFIDDLE
Try this:
var $locations = $("nav.sales-location").hide();
$("#sales-countries a").click(function () {
$locations.hide().filter(":eq(" + $(this).parent().index() + ")").show();
});
Demo: http://jsfiddle.net/bZLqR/1/
I did something like this kind of recently. This will do it even with Jquery.
var array = [ 1,2,3,4,5 ]
var list = document.getElementById('some-id');
function links(){ // generate links
for (var i in array){
var val = array[i];
var li = document.createELement('li');
li.innerHTML = "<a href='#'>" + val + "</a>"
li.onclick = show;
li.index = i; // save the array index for later
list.appendChild(li);
}
}
function show(e){
var index = e.target.index || -1 ;
var toShow = document.getElementsByClassName('class-name');
// hide all
for (var i in toShow){
toShow[i].style.visibility = 'hidden';
}
// show the one I want.
if (toShow.length < index && index >= 0){
toShow[index].style.visibility = 'visible';
}
}
links(); // build the links.

How to append the checkbox with the children div of a main div

I want to append a checkbox with each children.
For that I used
var len = $("#personalDetails").children("div").length;
for(var id=0; id<len;id++)
{
var el = $('<input type="checkbox"/>');
$("#personalDetails").children(":first").attr("id",id);
alert(id);
$( "#"+id).append(el);
}
html
<div id="personalDetails">
<div>personal</div>
<div>Education</div>
</div>
By doing this I got a problem. All checkboxes are coming under one div. How can I set one for one div and other for other div?
[Note: We can not put any id or class for children div]
http://jsfiddle.net/QTzrB/
you can
$(document).ready(function(){
$('#personalDetails > div').each(function(idx, el){
$('<input type="checkbox"/>').attr("id", idx).appendTo(el);
})
$('#personalDetails').on('click', 'input[type="checkbox"]', function(){
alert(this.id);
});
});
Demo: Fiddle
Try This
$(document).ready(function(){
var len = $("#personalDetails").children("div").length;
$("#personalDetails div").each(function(idx) {
$(this).append("<input type='checkbox' id="+ idx +" />");
});
$("input[type=checkbox]" ).on("click",function(){
alert($(this).attr("id"));
});
});
Fiddle Demo
You should cache the div list. Also if you don't want to put ids to the input elements then you can cache them also.
Below code is working on Fiddle.
$(document).ready(function(){
var divs = $("#personalDetails").children("div");
var len = divs.length;
for(var id = 0; id < len; id++) {
var el = $('<input type="checkbox"/>');
divs.eq(id).append(el);
}
});
replace your script with this one,hope this will do what you want.
$(document).ready(function(){
$('#personalDetails').children('div').each(function(){
$(this).append('<input type="checkbox"/>');
});
});
fiddle
$(document).ready(function(){
$("#personalDetails").children("div").each(function(index, obj) {
var $chk = $("<input/>",{"type":"checkbox"});
$(this).prepend($chk.attr("id",index));
$chk.on("click",function(){
alert(this.id);
});
});
});
Working demo here:
http://jsfiddle.net/HNezs/

Add class to <li> when clicking on a link

That's the html of my menu:
<ul class="nav">
<li>A</li>
<li><a href="#b" >B</a></li>
<li><a href="#c" >C</a></li>
<li><a href="#d" >D</a></li>
</ul>
I want that, after I clicked on a link in the menu, the active class will be added to the clicked <li>.
Thanks in advance
Use jquery
$("li a").click(function() {
$('li a').not(this).removeClass('active');
$(this).toggleClass('active');
});
DEMO Updated
He is not asking for a jQuery solution. But that jQuery would be the ideal choice, here is how to do it with javascript, best practices, event delegation and modern. Perhaps someone learns something new from it as well.
http://jsfiddle.net/N9Hem/
window.onload = function(){
(function(){
var els = [];
var doc = document;
var get = function(id){return doc.getElementById(id);};
get('clickable').onclick = function(evt){
evt = evt || window.event;
var el = evt.target || evt.srcElement;
els = doc.querySelectorAll('#clickable a');
if(el.nodeName == "A"){
for(var i = els.length - 1; i >= 0; i -= 1){
els[i].className = '';
};
el.className = 'active';
};
};
})();
};
If you use jQuery then you could use code like this:
$(function () {
$(".nav a").click(function () {
$(".nav a").removeClass("active");
$(this).addClass("active");
});
});
Try this with jQuery
$('#nav li a').click(function(){
$('#nav li a').removeClass('active');
$(this).addClass('active');
});
Here is a prototype that doesn't use jquery as you didn't request it on your question.
It searches for the current element with the active class, remove it and add the class to the clicked one.
Javasript Function
function activeThis(element){
var current = document.getElementsByClassName("active")[0];
current.className = null;
element.className="active";
}
HTML code
<a href="#b" onclick="activeThis(this)">
I hope I got what you want... I add eventHandlers to <ul>. On click remove clicked from previous elem and set clicked-class (if current class is active??)
<ul class="nav">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
<script>
var clickedElem = null;
document.getElementsByClassName("nav")[0].addEventListener("click", function (e) {
if (clickedElem)
clickedElem.removeAttribute("class");
// check if e.srcElement.className is active?? that's what you want?
e.srcElement.className = "clicked";
clickedElem = e.srcElement;
});
</script>
This one should works for you
elems =document.getElementsByClassName("nav")[0].getElementsByTagName("a");
for (var i = 0; i < elems.length; i++) {
elems[i].addEventListener("click", function (e) {
for (var i = 0; i < elems.length; i++) {
elems[i].className="";
};
this.className = "active";
});
}
I guess this will work
var navlinks = document.getElementByClass('nav').getElementsByTagName('a');
for (var i = 0; i < navlinks.length; i++) {
if(navlinks[i].className == 'active'){
navlinks[i].parentNode.parentNode.parentNode.className = 'YOUR CLASS';
}
}
Check my fiddle
I hope this is what you want
http://jsfiddle.net/arunberti/ftZzs/
a:visited
{
color:green;
}
a:active {color:yellow;}
a:link {color:red;}
Try this:
$('.nav li').click(function(e) {
$(this).addClass('selected').siblings().removeClass('selected');
});
Alternatively, if you want to attach the click event to the a:
$('.nav a').click(function(e) {
e.preventDefault();
$('.nav a').removeClass('selected');
$(this).addClass('selected');
});
Example fiddle
thats quite easy
jQuery CODE:
$('.nav li a').on('click',function(){
$('.nav li').each(function() {
var anc=$(this).find('a');
if(anc.hasClass('active'))
{
$(anc).removeClass('active');
}
})
$(this).addClass('active');
})
Edited:
Code is refined
Happy Coding :)

Categories