HTML append a class based on the name of current class JS - javascript

Is there a way to append a class to the current class name?
<li class="myWrap"></li>
Then onClick toggle class:
$('.myWrap').toggleClass('selected');
Is there anyway I can read the current class i've select and appended it to my one i'm adding. So my new class instead of:
<section class="myWrap selected"></section>
It will be:
<section class="myWrap myWrap_selected"></section>

.toggleClass() can already do this for you but you will need a way to determine the base class, because at any given point your elements can have more than one class (the base class, the selected class and any others). If you ensure that your base class will remain the first specified, then you can use the following.
$('li').on('click', function() {
// find the base class
var baseClass = $(this).attr('class').split(' ')[0];
// toggle the selected class
$(this).toggleClass(baseClass + '_selected');
});
$(function() {
$('li').on('click', function() {
var baseClass = $(this).attr('class').split(' ')[0];
$(this).toggleClass(baseClass + '_selected');
});
});
li.myClass {
border: 1px dashed red;
background-color: #ffcccc;
}
li.myClass_selected {
border-style:solid;
}
li.myWrap {
border: 1px dashed green;
background-color: #ccffcc;
}
li.myWrap_selected {
border-style:solid;
}
li.otherClass {
font-style:italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="myClass otherClass">Hello class</li>
<li class="myWrap otherClass">Hello wrap</li>
</ul>

Please try this function:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.myWrap').on('click', function() {
var newclass = $(this).attr('class') + "_selected";
$(this).toggleClass(newclass);
});
});
</script>

Related

jquery toggle between ID's based on element attribute

i have this
$(".picker").click(function(e) {
var imgID = $(this).attr("data-imgID");
$('body').addClass('picker-' + imgID);
});
<span class="taPicker" data-imgID="0"></span>
<span class="taPicker" data-imgID="1"></span>
<span class="taPicker" data-imgID="2"></span>
i want to toggle between generic classes on body element, for example if you click on .picker i want to add a unique class to body element based on the data-imgID attribute
But, how can i prevent the duplication's? for example if you click on another .picker i want to remove the previous class and add a new one
In your case you could do something like this:
var selectedClass = null;
$(".taPicker").click(function(e) {
var imgID = $(this).attr("data-imgID");
$('body').addClass('picker-' + imgID);
if (selectedClass != null) {
$('body').removeClass(selectedClass);
}
selectedClass = 'picker-' + imgID;
});
body.picker-0 {
background-color: pink;
}
body.picker-1 {
background-color: red;
}
body.picker-2 {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="taPicker" data-imgID="0">click 0</span>
<span class="taPicker" data-imgID="1">click 1</span>
<span class="taPicker" data-imgID="2">click 2</span>
Here is a fiddle
Another approach would be to determined the classes which need to be removed on each subsequent update. To this end, you can use a function which parses the current classes and removes any class which contains picker-, before setting the new class.
Here's what the JS code would look like:
function getPickerClasses(index, className) {
return className.split(' ').filter((classItem) => classItem.includes('picker-'));
}
$(".taPicker").click(function(e) {
var imgID = $(this).attr("data-imgID");
$('body').removeClass(getPickerClasses).addClass('picker-' + imgID);
});
This way, before setting the new class, the old one is removed.
Have a look at this fiddle to see the code in action: https://jsfiddle.net/0u24a1g3/
It can be done without adding extra global variable
$(".taPicker").click(function(e) {
var imgID = $(this).attr("data-imgID");
$('body').removeClass(function() {
return (this.className.match(/picker-./g) || []).join(' ');
});
$('body').addClass('picker-' + imgID);
});
body.picker-0 {
background-color: pink;
}
body.picker-1 {
background-color: red;
}
body.picker-2 {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="taPicker" data-imgID="0">click 0</span>
<span class="taPicker" data-imgID="1">click 1</span>
<span class="taPicker" data-imgID="2">click 2</span>
You can capture the original class(es) of body in a variable at DOM ready then use .removeClass() before re-adding back the original class plus the one based on the clicked element.
$(".taPicker").click(function(e) {
var imgID = $(this).attr("data-imgID");
var picker = $('body').attr("class").match(/picker-\d+/g) || [];
$('body').removeClass(picker).addClass('picker-' + imgID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="original">
<span class="taPicker" data-imgID="0">0</span>
<span class="taPicker" data-imgID="1">1</span>
<span class="taPicker" data-imgID="2">2</span>
</body>

jQuery insert after the last element

I want to add elements after the last one.
My current code
<div class="find"><div id="FirstElement"> /*First element loaded first */ </div><div>
$('#AddNextElement' + id).click(function (e) {
$('<div id="NextElement' + id +'">' + /*Add after the last element*/ + '</div>').insertAfter($("#FirstElement"));
}
Current it adds only it after the first element:
1
4
3
2
I want it to add after the last element every time:
1
2
3
4
I've followed these links and I didn't find what I'm looking for:
jQuery insertAfter last item
insertAfter specific element based on ID
jQuery: Add element after another element
Thank you in advance!.
How I fixed it:
$('#AddNextElement' + id).click(function (e) {
$('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>').insertAfter($("#FirstElement").parent().find('.Finder').last());
}
I found the .parent().find('.find').last(); then insert after the last
Just you need last() method
$('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>')
.insertAfter($('[id^="NextElement"]').last());
How about adding a class to all elements? It will be easier to find the last:
$('.element-class:last').after('<div class="element-class" id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>');
This of course means that your First element must also have the class:
<div class="element-class" id="FirstElement"> /*First element loaded first */ </div>
Find the last element in the DOM, in your case it'll be 'NextElementxx' and then use 'after':
$('#NextElement2').after( ..new stuff.. );
HTML:
<div id="FirstElement"> First element loaded first </div>
<div id="AddNextElement">Click me</div>
JS:
var current = 0;
$('#AddNextElement').click(function (e) {
var $el = (current == 0) ? $("#FirstElement") : $("#NextElement"+current);
current++;
$('<div id="NextElement' + current +'">Other element '+current+'</div>').insertAfter($el);
});
Try yourself on jsfiddle
You can just use this:
jQuery('##AddNextElement').last().after();
one way is to store the last element.
<div id="FirstElement"> /*First element loaded first */ </div>
var lastElement = $('#FirstElement');
$('#AddNextElement' + id).click(function (e) {
var element = $('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>'));
element.insertAfter(lastElement);
lastElement = element;
}
You can try below code, it will add the new div after the last "NextElement" div
JS Code:
$(function(){
$('#AddNextElementButton').on("click", function (e) {
var id = $("[id^='NextElement']").length ? $("[id^='NextElement']").length+1 : 1;
if($("[id^='NextElement']").length){
$('<div id="NextElement'+ id +'">Add after the last element</div>').insertAfter($('[id^="NextElement"]').last());
} else {
$('<div id="NextElement'+ id +'">Add after the last element</div>').insertAfter($('#FirstElement'));
}
});
});
**hope this will make you understand well GitHub:Omar-baksh **
// code by GitHub: omar-baksh
// jquery is required online !!
/*
//this scricp test if jquery loded
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
*/
var gfather = document.getElementsByClassName('Gfather');
var father = document.getElementsByClassName('father');
var son = document.getElementsByClassName('son');
function gf(argument) {
$(gfather).mouseenter(function(){
for (let i = 0; i < father.length; i++) {
father[i].style.display='block';
};
// show father fun() body show body last ...
});
$(father).mouseenter(function(){
for (let i = 0; i < son.length; i++) {
son[i].style.display='block';
};
// son show body last ...
});
// gf body last ...
}
// show form setting bottun fun()
function add(){
const x = document.getElementById("frm").style.display='block';
alert('setting opened');
}
// form add element fun()
var clslist=document.getElementsByClassName("list");
var inher =document.getElementById("level");
var num =document.getElementById("num").value;
var txt =document.getElementById("inp-text");
// var add-btn = document.getElementById("btn-secsuce");
/*
$("#inher").change(function () {
alert(inher);
document.getElementById("inp-text")="you selected"+ document.getElementById("level").value;
// body...
});
*/
var clss ="";
var ii;
$( "#btn-secsuce" ).click(function () {
//txt.value="class name "+inher.value;
if( String(inher.value) =="Grand father"){
clss ="Gfather";
jQuery('<div/>', {
id: Math.ceil(Math.random() * 999),
text:txt.value,
"class": clss,
title: clss+clss.length
}).appendTo(clslist);
alert("add class "+inher.value+gfather.length);
}
else { // alert("class enhhert is roung you chose " +inher.value )
}
/// add father to g father
if( String(inher.value) =="father"){
var txt2 = $("<div class="+"father"+"></div>").text(txt.value);
$(father[num-1]).after(txt2);
}
else{
}
});
.Gfather{
width: 60px;
height: auto;
border-left: 6px dashed red;
border-bottom: 6px dashed red;
 background-color: silver;
top:0;
display:block;
position:relative ;
margin-left:9px;
white-space: nowrap;
}
.father{
width: 60px;
border-left: 6px dashed red;
border-bottom: 6px dashed red;
bottom:0;
padding-top:0px;
border-right-width: small;
left:66px;
white-space: nowrap;
position:relative ;
background-color: #550088;
color:white;
display: block;
}
<head>
<title>tree js</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="./tree.css">
</head>
<body>
<div class="list">
<div class ="Gfather" onmouseover="gf();">
grand father 1
</div>
<div class ="father">
father
</div>
<div class ="son">son
</div>
<div class ="son">son
</div>
</div>
<!-- add element show setting btn -->
<button id="add" onclick="add()" > add setting</button>
<form id="frm">
<h6>1</h6>
<select id="level">
<option>Grand father</option>
<option>father</option>
<option>son</option>
</select>
<h6>2</h6>
<select id="num">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
</select>
<br>
<h6>3</h6>
<input id="inp-text" type="text">
<h5 >4</h5>
<button type="button" id="btn-secsuce" >Add The Element </button>
</form>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script type="text/javascript" src="./tree.js"></script>

How to activate menu tab after refreshing

How can I activate a menu tab after refreshing?
Here are my code
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
.menu{width: 600px; height: 25; font-size: 18px;}
.menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
.menu li:hover, .menu li.active {
background-color: #f90;
}
</style>
</head>
<body>
<ul class="menu">
<li><a href='#'>One</a></li>
<li><a href='#'>Two</a></li>
<li><a href='#'>Three</a></li>
<li><a href='#'>Four</a></li>
</ul>
<script type="text/javascript">
var make_button_active = function()
{
//Get item siblings
var siblings =($(this).siblings());
//Remove active class on all buttons
siblings.each(function (index)
{
$(this).removeClass('active');
}
)
//Add the clicked button class
$(this).addClass('active');
}
//Attach events to menu
$(document).ready(
function()
{
$(".menu li").click(make_button_active);
}
)
</script>
Can anyone tell me How to resolve this issue ?
Just like #Johan said, store your last active tab in a localStorage or cookie. Since there is no noticeable difference in performance between the two. I suggest you use localStorage because it's much easier to use. Like this:
function make_button_active(tab) {
//Get item siblings
var siblings = tab.siblings();
//Remove active class on all buttons
siblings.each(function(){
$(this).removeClass('active');
})
//Add the clicked button class
tab.addClass('active');
}
//Attach events to menu
$(document).ready(function(){
if(localStorage){
var ind = localStorage['tab']
make_button_active($('.menu li').eq(ind));
}
$(".menu li").click(function () {
if(localStorage){
localStorage['tab'] = $(this).index();
}
make_button_active($(this));
});
});
Check out this fiddle.

Dynamically assigning border radius to the li first-child in Javascript

I am trying to create a navigation bar with rounded corners for the first and last children (using an unordered list). I want to use the onclick javascript function and dynamically assign rounded corners within javascript. Here is my code which I tried. Can anyone please point me to the reason and/or suggest a solution or resource? Thanks a lot in advance.
HTML:
<nav>
<ul id="navBar">
<li><div class="menu" onClick="select(this)">View</div></li>
<li><div class="menu" onClick="select(this)">Duplicate</div></li>
<li><div class="menu" onClick="select(this)">Edit</div></li>
<li><div class="menu" onClick="select(this)">Delete</div></li>
</ul>
</nav>
Javascript:
document.getElementById('ul#navBar li:first-child').style.MozBorderRadiusTopleft = '13px';
document.getElementById('ul#navBar li:first-child').style.MozBorderRadiusBottomleft = '13px';
document.getElementById('ul#navBar li:last-child').style.MozBorderRadiusTopRight = '13px';
document.getElementById('ul#navBar li:last-child').style.MozBorderRadiusBottomRight = '13px';
CSS for your stylesheet:
.is-rounded li:first-child {
-moz-border-radius: 13px 0 0 13px;
-webkit-border-radius: 13px 0 0 13px;
border-radius: 13px 0 0 13px;
}
.is-rounded li:last-child {
-moz-border-radius: 0 13px 13px 0;
-webkit-border-radius: 0 13px 13px 0;
border-radius: 0 13px 13px 0;
}
Javascript:
function makeRounded(e) {
document.querySelector('#navBar').className += 'is-rounded';
}
document.querySelector('#el').addEventListener('click', makeRounded, false);
This assumes than an element with the id of "el" is the element that, when clicked, triggers the whole thing.
See example: http://jsfiddle.net/cgrFe/3/
You seem to know very little about this. A few books to get you started: http://domscripting.com/book/ and http://domenlightenment.com/ . The last of the two is fairly new, but must be good.
getElementById does not take a selector as its argument. Only a valid id of the element is required for its usage. You're probably thinking about jQuery:
$('ul#navBar li:first-child').css({
MozBorderRadiusTopleft: '13px'
});
$('navBar li:first-child').css({
MozBorderRadiusBottomleft: '13px'
});
$('ul#navBar li:last-child').css({
MozBorderRadiusTopRight: '13px'
});
$('navBar li:last-child').css({
MozBorderRadiusBottomRight: '13px'
});
I would make things really simple. Start by defining two css classes for rounded corners:
.round-top {
MozBorderRadiusTopleft:13px;
MozBorderRadiusTopRight:13px;
}
.round-bottom {
MozBorderRadiusBottomleft:13px;
MozBorderRadiusBottomRight:13px;
}
Then you can simply add/remove the class from the elements that you are interested in.
In javascript:
var container = document.getElementById(navBar);
container.firstChild.setAttribute("class", "round-top");
container.lastChild.serAttribute("class", "round-bottom");
Jquery:
$('#navBar li:first-child').addClass('round-top');
$('#navBar li:last-child').addClass('round-bottom');
A full event listener would be something like:
function addBorders(){
var container = document.getElementById(navBar);
container.firstChild.setAttribute("class", "round-top");
container.lastChild.serAttribute("class", "round-bottom");
}
//target is the element you want to trigger the event
target.addEventListener("click", addBorders, false);
If you can use jquery, you can do it in next way
intead "border", "3px double red" you should use your styles
<script type="text/javascript" language="javascript">
var Menu = {
rootEl: null,
Init: function (idRootEl) {
this.rootEl = $(idRootEl);
this.initItems();
this.setFirstElSeleceted();
},
setFirstElSeleceted: function () {
$($(this.rootEl).find('li')[0]).css("border", "3px double red");
},
initItems: function () {
var self = this;
$(self.rootEl).find('li').each(function (indx) {
$(this).click(function () {
self.removeSelection();
self.setSelected(this);
});
});
},
setSelected: function (el) {
$(el).css("border", "3px double red");
},
removeSelection: function () {
var self = this;
$(self.rootEl).find('li').each(function (el) {
$(this).css("border", "");
});
}
};
$(function() {
Menu.Init('ul#navBar');
});
</script>

How to convert unordered list into nicely styled <select> dropdown using jquery?

How do I convert an unordered list in this format
<ul class="selectdropdown">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
<li>seven</li>
</ul>
into a dropdown in this format
<select>
<option value="one.html" target="_blank">one</option>
<option value="two.html" target="_blank">two</option>
<option value="three.html" target="_blank">three</option>
<option value="four.html" target="_blank">four</option>
<option value="five.html" target="_blank">five</option>
<option value="six.html" target="_blank">six</option>
<option value="seven.html" target="_blank">seven</option>
</select>
using jQuery?
Edit: When selecting an entry from the select/dropdown the link should open in a new window or tab automatically. I also want to able to style it like: http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/
$(function() {
$('ul.selectdropdown').each(function() {
var $select = $('<select />');
$(this).find('a').each(function() {
var $option = $('<option />');
$option.attr('value', $(this).attr('href')).html($(this).html());
$select.append($option);
});
$(this).replaceWith($select);
});
});
EDIT
As with any jQuery code you want to run on page load, you have to wrap it inside $(document).ready(function() { ... }); block, or inside it's shorter version $(function() { ... });. I updated the function to show this.
EDIT
There was a bug in my code also, tried to take href from the li element.
$('ul.selectdropdown').each(function() {
var select = $(document.createElement('select')).insertBefore($(this).hide());
$('>li a', this).each(function() {
var a = $(this).click(function() {
if ($(this).attr('target')==='_blank') {
window.open(this.href);
}
else {
window.location.href = this.href;
}
}),
option = $(document.createElement('option')).appendTo(select).val(this.href).html($(this).html()).click(function() {
a.click();
});
});
});
In reply to your last comment, I modified it a little bit but haven't tested it. Let me know.
$('ul.selectdropdown').each(function() {
var list = $(this), select = $(document.createElement('select')).insertBefore($(this).hide());
$('>li a', this).each(function() {
var target = $(this).attr('target'),
option = $(document.createElement('option'))
.appendTo(select)
.val(this.href)
.html($(this).html())
.click(function(){
if(target==='_blank') {
window.open($(this).val());
}
else {
window.location.href = $(this).val();
}
});
});
list.remove();
});
This solution is working also in IE and working with selected item (in anchor tag).
$('ul.selectdropdown').each(function(){
var list=$(this),
select=$(document.createElement('select')).insertBefore($(this).hide()).change(function(){
window.location.href=$(this).val();
});
$('>li a', this).each(function(){
var option=$(document.createElement('option'))
.appendTo(select)
.val(this.href)
.html($(this).html());
if($(this).attr('class') === 'selected'){
option.attr('selected','selected');
}
});
list.remove();
});
Thank you all for posting the codes. My scenario is similar but my situation is for Responsiveness that for x-size it would switch to a dropdown list, then if not x-size, using csswatch to check for the "display" properties of an element that has certain amount of width set to it (eg: 740px). Thought I share this solution for anyone who is interested. This is what I have combined with Tatu' codes. Instead of replacing the html, I created then hide the new html then only add them when necessary:
var $list = $('ul.list');
(listFunc = function(display){
//Less than x-size turns it into a dropdown list
if(display == 'block'){
$list.hide();
if($('.sels').length){
$('.sels').show();
} else {
var $select = $('<select class="sels" />');
$list.find('a').each(function() {
var $option = $('<option />');
$option.attr('value', $(this).attr('href')).html($(this).html());
$select.append($option);
});
$select.insertAfter($list);
$('.sels').on('change', function(){
window.location = this.value;
});
}
} else {
$('.sels').hide();
$list.show();
}
})(element.css('display'));
element.csswatch({
props: 'display'
}).on('css-change', function (event, change) {
return listFunc(change.display);
});
I have recently created a solution where the ul transformed, mimics nearly completely the select.
It has in adition a search for the options of the select and supports the active state. Just add a class with name active and that option will be selected.
It handles the keyboard navigation.
Take a look at the code here: GitHub Code
And a live example here: Code Example
The unordered list must be in the form:
<ul id="...">
<li>...</li>
<li>...</li>
<li><a class="active" href="...">...</a></li>
...
</ul>
To convert the ul to select just call:
$(window).on("load resize", function() {
ulToSelect($("ul#id"), 767);
});
Where #id is an id for the unordered list and 767 is the minimum width of the window for the convertion to take place. This is very useful if you want the convertion to take place only for mobile or tablet.
I found this gorgeous CodePen from #nuckecy for anyone interested:
https://codepen.io/nuckecy/pen/ErPqQm
$(".select").click(function() {
var is_open = $(this).hasClass("open");
if (is_open) {
$(this).removeClass("open");
} else {
$(this).addClass("open");
}
});
$(".select li").click(function() {
var selected_value = $(this).html();
var first_li = $(".select li:first-child").html();
$(".select li:first-child").html(selected_value);
$(this).html(first_li);
});
$(document).mouseup(function(event) {
var target = event.target;
var select = $(".select");
if (!select.is(target) && select.has(target).length === 0) {
select.removeClass("open");
}
});
His default CSS rules:
.select li {
display: none;
cursor: pointer;
padding: 5px 10px;
border-top: 1px solid black;
min-width: 150px;
}
.select li:first-child {
display: block;
border-top: 0px;
}
.select {
border: 1px solid black;
display: inline-block;
padding: 0;
border-radius: 4px;
position: relative;
}
.select li:hover {
background-color: #ddd;
}
.select li:first-child:hover {
background-color: transparent;
}
.select.open li {
display: block;
}
.select span:before {
position: absolute;
top: 5px;
right: 15px;
content: "\2193";
}
.select.open span:before {
content: "\2191";
}

Categories