Do something if element has class - javascript

Here is what I want to do...First if you click the "All" li box it adds and removes a red border around all the other boxes. Now I want it so that if a box containing a red border is clicked then simply toggle the class .box-border.
<style>
.box { width: 100px; height: 100px; background: beige; }
.box.select-all { background: #333; color: white; }
.box-border { border: 1px solid red; }
ul li {
display: inline;
list-style: none;
float: left;
margin: 0 5px;
text-align: center;
line-height: 100px;
}
</style>
<div class="row">
<div class="large-10 push-2 medium-10 columns">
<ul>
<li class="box box1"></li>
<li class="box box2"></li>
<li class="box box3"></li>
<li class="box box4"></li>
<li class="box box5 select-all">All</li>
</ul>
</div>
</div>
<script>
$(document).ready(function(){
var selectAll = $('.box.select-all');
var boxes = $('.box').not(selectAll);
selectAll.click(function(){
boxes.toggleClass('box-border');
// if (boxes.hasClass('box-border')) {
// console.log('yes');
// }
});
$('ul li').click(function(){
var item = $(this).index();
if (item.hasClass('box-border')) {
console.log('yessssss');
}
});
});
</script>

You need to use $(this).hasClass('box-border')
As per your code, item will be a integer referring to elements index.
var item = $(this).index();
Modified Code:
$('ul li').click(function(){
var item = $(this).index();
if ($(this).hasClass('box-border')) {
console.log('yessssss');
}
});
EDIT
If you want to use toggleClass()
$('ul li').click(function(){
var item = $(this).index();
$(this).toggleClass('box-border');
});

I wrote this (with jQuery) to toggle between two pages upon clicking a button with a class (the class is removed if it is present, and added if it is absent to use the same button (element with the same ID) again),
the order of the method calls and 'innerHTML' property setting does matter in the function (you must make changes to the page(or other changed element) before you make changes to the button (or other event 'triggered' element)), and the order in which you add the 'mPage' class (the triggering class) to the button does not matter.
<script id="toSettings">
const spage = document.getElementById("mContent");
$( "#setsBtn" ).click(function(){
if ($(this).hasClass('mPage')) {
spage.innerHTML = '';
spage.innerHTML = '<br /><div style="width=100%; height=100%; top=0; left=0; background-color: pink;"> <button class="w3-btn w3-amber" onclick="goso()">dest</button><br /> <button class="w3-btn w3-amber">dest</button><br /><button class="w3-btn w3-amber">dest</button> </div>';
this.innerHTML = '<img src="img/leftarrow.svg"/>'
this.classList.remove('mPage');
}
else {
spage.innerHTML='';
spage.innerHTML = '<div style="width: 100%; height: 100%; " id="mContent" class="mContent w3-center"><br /><br /><br /><br /><br /><br /><br /><div id="" class=""><div class="mPageBtn w3-button w3-green" id="ledgerbtn" style="display: block;">Ledger</div><br /></div>';
this.classList.add('mPage');
this.innerHTML = '<img src="img/gear.svg"/>';
}
});
</script>
The 'w3' classes are part of the w3-css library available on w3schools.com .

Related

Create multiple divs with different content

The problem is when duplicate multiple div but with different data-type, it still running a same content, i want correct all div will have the different content following the different data-type.
Is there a way to do this?
$(function() {
// document
'use strict';
var cp = $('div.box');
// unique id
var idCp = 0;
for (var i = 0; i < cp.length; i++) {
idCp++;
cp[i].id = "cp_" + idCp;
}
// diffrent type
if (cp.data('type') == "c1") {
cp.addClass('red').css({
"background: 'red',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c1-title' + '</div>');
} else if (cp.data('type') == "c2") {
cp.addClass('green').css({
"background": 'green',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c2-title' + '</div>');
} else {
return false;
}
}); //end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<! it should be like this>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c2 title</div>
</div>
<! currently wrong output>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c1 title</div>
</div>
The problem in your code is that you are not looping inside the div's. You have to use the .each() function while looping inside all the elements
$(function() {
var cp = $('div.box');
cp.each(function() {
var _cp = $(this);
var text = _cp.attr("data-type") + "-title"; //Generate the text dynamically
var cls = _cp.attr("data-class"); //Get the class dynamically
_cp.addClass(cls).append('<div class="cp-title">' + text + '</div>'); //Add the class and append the text to the parent div
});
}); //end
.box{
padding: 20px;
display: table;
}
.red{
background: red;
}
.green{
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1" data-class="red"></div>
<div class="box" data-type="c2" data-class="green"></div>
Probably you're searching for something like this.
// document.ready
$(function() {
'use strict';
$('.box').each(function(i,elem){
var ref = +$(elem).attr("data-type").match(/\d/)[0], addClass = 'default';
switch(true) {
case ref === 1:
addClass = 'red';
break;
case ref === 2:
addClass = 'green';
break;
}
$(this)
.addClass(addClass)
.append('<div class="cp-title">c'+ref+' title</div>');
});
}); //end
.red{
background: red;
padding: 20px;
display: table;
}.green{
background: green;
padding: 20px;
display: table;
}.default {
background: #2d2d2d;
color: #f6f6f6;
padding: 20px;
display: table;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1"></div><div class="box" data-type="c2"></div>

How to create dynamic content with relative IDs using different buttons, inputs or links?

It seems to be easy, but it might be harder than it looks like, maybe. I've been having a hard time with this one.
What I'm trying to accomplish here is to create dynamic content with IDs, when clicking on any button, input or link using jQuery.
To explain better,
If .button-2 or .input-2 or .link-2 has been clicked, then the content dynamically created should be Content-1 and not Content-2 (I've got this part working right).
Then, If .button-1 or .input-1 or .link-1 gets clicked after, another content gets dynamically created and should be Content-2 (and not Content-1) and so on... (this part is also working fine)
If there is only 3 different elements I'm targeting, then only 3 contents should be created and not more. Unless I add another different target element and so on... (I need help with this)
The target elements could (but is not necessary) be clicked as of an unorderly way and still have the content with an ordered ID. (This working fine too)
In other words, you don't have to click the target elements as of an orderly way to have the content with an ordered ID.
Jsfiddle example
This code was created as an example of the main code
$(function() {
var num = 1;
$("button").on("click", function() {
$("<div />").attr("id", num).text("Content-" + num)
.appendTo($(".inner"));
num++;
});
});
.inner {
margin-top: 50px;
padding: 50px;
border: 1px solid #CCC;
}
.inner div {
background: #d0cfcf;
padding: 10px;
margin-bottom: 10px;
font-size: 22px;
color: #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="container">
<button type="button" class="button-1">btn 1</button>
<button type="button" class="button-2">btn 2</button>
<button type="button" class="button-3">btn 3</button>
</div>
<div class="container-2">
<input type="text" class="input-1" value="click me">
<input type="text" class="input-2" value="click on me too">
</div>
<div class="container-3">
Click here
Click here
</div>
<div class="inner"></div>
This question has been updated
Counting the buttons to answer the original question:
$(function() {
var num = 1;
$("button").on("click", function() {
if ($(".inner").children().length>=$(".container").children().length) return
$("<div />").attr("id", num).text("Content-" + num)
.appendTo($(".inner"));
num++;
});
});
.inner {
margin-top: 50px;
padding: 50px;
border: 1px solid #CCC;
}
.inner div {
background: #d0cfcf;
padding: 10px;
margin-bottom: 10px;
font-size: 22px;
color: #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="container">
<button type="button">btn 1</button>
<button type="button">btn 2</button>
<button type="button">btn 3</button>
</div>
<div class="inner"></div>
Here's a hardcoded, simple example.
var num = 1;
$( "button" ).on( "click", function() {
if( num === 1) {
num++;
$( "<div />" ).attr( "id", num ).text( "Content-" + num ).appendTo( $( ".inner" ) );
return;
}
if( num === 2) {
num--;
$( "<div />" ).attr( "id", num ).text( "Content-" + num ).appendTo( $( ".inner" ) );
return;
}
if( num === 3) {
num--;
$( "<div />" ).attr( "id", num ).text( "Content-" + num ).appendTo( $( ".inner" ) );
return;
}
});

swap div's position from top div's

I am trying to swap a div's position from top on and when I click another div then top div can be swap.
HTML
<div class="wrap top">
<input type="text" value="div1" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div2" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div3" class="textbox " />
</div>
jQuery
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(this).insertBefore($(this).prev());
}
});
}(jQuery));
The fact is I don't want to remove the div which I click instead want to swap the positions around.
How Can I do this using jQuery itself?
I would suggest using css to position the top div and just swap the class as follows:
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(".wrap").removeClass("top");
$(this).addClass("top");
}
});
}(jQuery));
this will swap whatever you click with the first element.
$(".wrap").on("click", function () {
var $this = $(this);
if ($this.index() == 0) {
} else {
var first = $this.siblings('.wrap').first();
first.insertBefore($this);
$this.prependTo($this.parent());
}
});
if you just want to move the clicked element to the top, you can simply do
$this.prependTo($this.parent());
To swap the two DOM elements using jQuery, you could use something like this: -
(function($) {
$(".wrap").on("click", function(event) {
var index = $(event.target).index();
var first = $(".wrap").first();
if (index > 0) {
$(first).swapWith(this);
}
});
}(jQuery));
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
.wrap {
height: 100px;
width: 200px;
margin: 10px 10px 10px 10px;
background-color: #2d8cd0;
}
h2 {
color: white;
text-align: center;
padding-top: 20px;
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="wrap">
<h2>1</h2>
</div>
<div class="wrap">
<h2>2</h2>
</div>
<div class="wrap">
<h2>3</h2>
</div>
<div class="wrap">
<h2>4</h2>
</div>

Generic Javascript Code

I wrote a code for a hover functionality. Now, I am asking myself how to make this code generic in order to show different divs when hovering over a different link. The JavaScript code is as follows:
<script>
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('a#trigger').hover(function(e) {
$('div#purpose').show();
}, function() {
$('div#purpose').hide();
});
$('a#trigger').mousemove(function(e) {
$("div#purpose").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
});
</script>
The div I call is as follows:
<!-- Purpose: Hover Popup -->
<div class= id="purpose">
<h3>Purpose</h3>
<p>
Test
</p>
</div>
Furthermore, I added some CSS style
<!-- Style for Hovering -->
<style type="text/css">
div#purpose {
display: none;
position: absolute;
width: 280px;
padding: 10px;
background: #eeeeee;
color: #000000;
border: 1px solid #1a1a1a;
font-size: 90%;
}
</style>
Could anybody tell me how to make this code generic in order to add further divs which are called from another link?
Create a javascript function and pass in the variables (e.g. link and div)
function foo($link, $div){
var moveLeft = 20;
var moveDown = 10;
$link.hover(function(e) {
$div.show();
}, function() {
$div.hide();
});
$link.mousemove(function(e) {
$div.css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
}
For your existing behaviour call the following for example:
foo($('a#trigger'), $("div#purpose"));
This will actually be slightly better for performance as you'll be using the same jQuery reference each time. However depending on how you're actually planning on using this, having a seperate function call each time might not be the best way.
For example if you wish to use this on dynamic data it wouldn't be sensible to make static calls to a function each time.
Make use of custom data-* attributes in your HTML, and use classes to target a generalized group of elements, ex:
<a class="trigger" data-target="purpose" />
And the JS
$(".trigger").hover(function(e) {
var elemToShow = $(this).data("target");
$("#" + elemToShow).show();
}, function() {
var elemToShow = $(this).data("target");
$("#" + elemToShow).show();
}).mousemove(function(e) {
var elemToShow = $(this).data("target");
$("#" + elemToShow).css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
You could build your trigger elements in a way that they hold the information about what element to show:
<a class="trigger" data-show="purpose">...</a>
Then you initialize them all at once like this:
$(function() {
$('.trigger').hover(function() {
var elementId = $(this).data('show');
$('#'+elementId).show();
}, function() {
var elementId = $(this).data('show');
$('#'+elementId).hide();
);
});
You don't need any JavaScript or jQuery at all for this--you can simply use CSS with the :hover pseudo-class.
.menu {
background-color: #eee;
}
.menuItem {
display: inline-block;
}
.menu .trigger + .purpose {
display: none;
position: absolute;
background-color: #eee;
}
.menu .trigger:hover + .purpose, .menu .trigger + .purpose:hover {
display: block;
}
<div class="menu">
<div class="menuItem">
Trigger 1
<div class="purpose">
<h3>Purpose 1</h3>
<p>
Test 1
</p>
</div>
</div>
<div class="menuItem">
Trigger 2
<div class="purpose">
<h3>Purpose 2</h3>
<p>
Test 2
</p>
</div>
</div>
<div class="menuItem">
Trigger 3
<div class="purpose">
<h3>Purpose 3</h3>
<p>
Test 3
</p>
</div>
</div>
<div class="menuItem">
Trigger 4
<div class="purpose">
<h3>Purpose 4</h3>
<p>
Test 4
</p>
</div>
</div>
</div>

How to wrap div element around newly typed text so that associated css result will be shown in real time

I have created a simple text editor which shows the associated CSS results in real time. for example if a user clicks Bold Then text becomes bold while user is typing (it shows real time change). Same like this I want a button after click it will wrap the new text with a div tag with specified class or id.
I know wrap method can wrap the div or other tag. But after adding new div tags through wrap() I want store its result which contains newly added div tags. so that I can use those result to generate new html pages.
Here is the html code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="texteditor.js"></script>
</head>
<body>
<div id="content" style="margin-top: 10px; height: 70%; text-align: center;">
<h2><u>Simple Text Editor Created Using jQuery</u></h2>
<div class="ze ie"></div>
<style>
.font-bold.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
.selected {
background-color: orange;
}
#openpb {
margin: 15px;
}
</style>
<button type="button" class="g-button g-button-submit" id='stext'>Text</button>
<button type="button" class="g-button g-button-submit" id='shtml'>HTML</button>
<div id="controls" style="margin-bottom: 10px;">
<a id="bold" style="color: black; display: inline-block;" class="font-bold">
<button type="button">B</button>
</a>
<a id="italic" style="color: black !important; display: inline-block;" class="italic">
<button type="button">I</button>
</a>
<a id="link" class="link" style="display: inline-block;">
<button type="button">Link</button>
</a>
<select id="fonts" class="g-button">
<option value="Normal">Normal</option>
<option value="Arial">Arial</option>
<option value="Comic Sans MS">Comic Sans MS</option>
<option value="Courier New">Courier New</option>
<option value="Monotype Corsiva">Monotype</option>
<option value="Tahoma New">Tahoma</option>
<option value="Times">Times</option>
<option value="Trebuchet New">Trebuchet</option>
<option value="Ubuntu">Ubuntu</option>
</select>
</div>
<iframe frameborder="0" id="textEditor" style="width: 500px; height: 80px; border: 2px solid #CCC; border-radius: 20px; overflow: auto;"></iframe>
<textarea name="text" id='text' style="border-radius: 20px; overflow: auto; display: none; padding-left: 10px;" rows="6" cols="53"></textarea>
</div>
</body>
</html>
here is Jquery: as you can I have used setinterval method to show result in real time in textarea. same like this I want a button which will wrap new or selected text with div tag with specified id and class and I want store this changes(newly added div tag) in textarea.
$(document).ready(function () {
document.getElementById('textEditor').contentWindow.document.designMode = "on";
document.getElementById('textEditor').contentWindow.document.close();
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
$("#bold").click(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
boldIt();
});
$("#italic").click(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
ItalicIt();
});
$("#fonts").on('change', function () {
changeFont($("#fonts").val());
});
$("#link").click(function () {
var urlp = prompt("What is the link:", "http://");
url(urlp);
});
$("#stext").click(function () {
$("#text").hide();
$("#textEditor").show();
$("#controls").show()
});
$("#shtml").on('click', function () {
$("#text").css("display", "block");
$("#textEditor").hide();
$("#controls").hide();
});
});
function boldIt() {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("bold", false, "");
edit.focus();
}
function ItalicIt() {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("italic", false, "");
edit.focus();
}
function changeFont(font) {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("FontName", false, font);
edit.focus();
}
function url(url) {
var edit = document.getElementById("textEditor").contentWindow;
edit.focus();
edit.document.execCommand("Createlink", false, url);
edit.focus();
}
setInterval(function () {
var gyt = $("#textEditor").contents().find("body").html().match(/#/g);
if ($("#textEditor").contents().find("body").html().match(/#/g) >= 0) { } else {
$("#text").val($("#textEditor").contents().find("body").html());
}
$("#text").val($("#textEditor").contents().find("body").html());
}, 1000);
I don't want use third party text editor plugins. in short I want texteditor which contain a button, after clicking this button it will wrap new text with div tag with specified class or id. something like Stack Overflow text editor...with facility of adding custom div with specified class or id.
<html>
<head>
<style>
#Problem{margin: 5px; outline: 1px dotted red; padding: 5px}
#Solution{margin: 5px; outline: 1px dotted green; padding: 5px}
#Solution textarea{
height: 200px;
width: 500px;
}
</style>
<script>
//Wraps the text in a new div with optional id and classname.
//Returns the new div.
function wrapMe(text, id, classname){
var tE = null;
if (text && text.trim() != ''){
tE = document.createElement('div');
tE.id = (id || '');
tE.className = (classname || '');
tE.innerHTML = (text || '');
}
return tE
}
//Adds the outer html of passed element to the textarea with a linebreak
function addElementToTextarea(e){
var tA = document.querySelector('textarea');
if (tA && e){
tA.innerHTML = (tA.innerHTML || '') + e.outerHTML + '
&#010'
}
}
</script>
</head>
<body>
<div id = 'Problem'>
Problem: I don't want use third party text editor plugins. in short i want texteditor which contain a button, after clicking this button it will wrap new text with div tag with specified class or id. something like stackover flow text editor...with facility of adding custom div with speicifed class or id.
</div>
<div id = 'Solution'>
<input type = 'text' />
<button onclick = "addElementToTextarea(wrapMe(this.parentNode.querySelector('input').value, 'testid', 'testclass'))">Wrap me</button>
<br /><br />
<textarea readonly = 'readonly'></textarea>
</div>
</body>
</html>

Categories

Resources