Create my own Radio-like-button with a DIV? - javascript

I'm trying to make a site where users can create there own social networking buttons. (I know its been done but its mostly for practice). A part of the site will allow users to choose the shape of the buttons. Here is the HTML:
<div class="design" id="shape">
<div class="shapeSelect square" id="square"></div>
<div class="shapeSelect rounded" id="rounded"></div>
<div class="shapeSelect circle" id="circle"></div>
</div>
What I would like to do is add an event listener when the div is clicked. After it's clicked the class attribute would be changed to "selected." When another one would be click then the first clicked one would be cleared and the next one would be selected. Just like with radio buttons.
I am familiar with JavaScript and my idea was this:
window.onload = function () {
'use strict';
document.getElementById("square").addEventListener('click', function (e) {//adds the event listener
divArray = document.getElementById("shape");//Here is my first issue: an array is not returned
if (!(document.getElementById("square").getAttribute("class") == "shapeSelect square selected")) {// checks to make sure its not already selected
for (i = 0, count = document.getElementById("shape").length; i < count; i++) {// if it isn't go through the array
divArray[i]// and this is where i also get stuck. I Can't figure out how i would return the class attribute to be class="shapeSelect circle" instead of class="shapeSelect circle selected"
};
}
}, false);
}

A more simple version of scdavis41's answer:
$(document).ready(function(){
$('#shape > .shapeSelect').click(function(){
$('#shape > .shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
I also put a selector that includes the control's main div id in case you want to put this control more then once in your page.
** EDIT **
If you absolutly want to use javascript and DOM try this:
document.getElementById("square").addEventListener('click', function (e) {
var divArray = document.getElementById("shape").getElementsByTagName("div"); //Get all the div child element of the main div
for (i = 0, count = divArray.length; i < count; i++) {
if(divArray[i].getAttribute("class").indexOf("selected") !== -1) { //check if the selected class is contained in the attribute
divArray[i].setAttribute("class", divArray[i].getAttribute("class").replace("selected", "")); // clear the selected class from the attribute
}
};
document.getElementById("square").setAttribute("class", document.getElementById("square").getAttribute("class").concat(" selected")); //select the square
}, false);

This is verbose, but you could use:
$(document).ready(function(){
$('#square').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#circle').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#rounded').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
This is jQuery, which means you have to load the jQuery library, but putting this above your script tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

If you are looking for a pure JavaScript solution, you could try this:
if(option == 'add'){
element.className = element.className + ' selected';
element.onclick = function() {select(this.id, 'remove')};
element.innerHTML = '✓';
}
else if(option == 'remove'){
element.className = element.className.replace(/\bselected\b/,'');
element.onclick = function() {select(this.id, 'add')};
element.innerHTML = '';
}
JSFiddle: http://jsfiddle.net/hKePD/
**EDIT**
Or if you were looking for a checkbox to be always checked, you could try this: http://jsfiddle.net/hKePD/1/

Building on scadvis41's answer, this is much shorter:
$(document).ready(function(){
$('.shapeSelect').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});

Related

How to hide div after page loads in plain Javascript?

I've viewed a couple of the posts in here regarding this topic but not quite working for my situation. I'm using Tampermonkey userscript manager. I want to hide a bunch of div's after the page is fully loaded. I've tested the code below on the console of the page and it works.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
This alert also works with the Tampermonkey userscript manager.
window.addEventListener("load", function(){
// code goes below
alert("hello world");
});
However, the following code is not working. Neither the div or the alert is working in this situation.
window.addEventListener("load", function(){
// ....
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
alert("it's working");
});
By the way, I'm a newbie to Javascript so any help is much appreciated.
You currently only hide the first ([0]) div. You need to iterate over all elements to hide them.
I'd suggest using document.querySelectorAll because it's easily iterable:
window.addEventListener("load", function(){
document.querySelectorAll('promotions-personalized-offers-ui-single-offer')
.forEach(e => (e.style.display = 'none'));
});
If you must stick to getElementsByClassName, a spread should do the trick:
window.addEventListener("load", function(){
[...document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')]
.forEach(e => (e.style.display = 'none'));
});
Try this:
var x = 3 //number of div elements to remove
window.onload = function() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
The divs would need to look like this:
<div id="div1">Content</div>
<div id="div2">Content</div>
<div id="div3">Content</div>
Alternatively, if you're putting the JavaScript code inside a function that's called after the page loads fully, you can just use this:
var x = 3 //number of div elements to remove
function removeDivs() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
Then call the function by using removeDivs().
Tampermonkey by default runs when the DOMContentLoaded event is dispatched. https://www.tampermonkey.net/documentation.php#_run_at Based on what you have posted it does not look like you need the event listener at all. Your script would only need one line.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';

Scope issues inside an Event Listener?

The following code basically shows/hides paragraph tags, I'm having to re-declare the paras variable. Is this because I'm dynamically injecting the button into the DOM, or is it to do with scope? How could I better construct this markup?
// vars
var revealContainer = document.querySelector('.reveal-more');
var paras = revealContainer.querySelectorAll('p');
var status = true;
// return
if (paras && paras.length <= 3) return;
// generate show more link
revealContainer.innerHTML += '<button class="button--text reveal-more__btn">Read more</button>';
var revealBtn = revealContainer.querySelector('.reveal-more__btn');
// click event
revealBtn.addEventListener('click', function () {
var paras = revealContainer.querySelectorAll('p');
// toggle show/hide class
for (var i = 0; i < paras.length; i++) {
var p = paras[i];
p.classList.toggle('is-shown');
}
// check status
if (status) {
this.textContent = 'Read less';
status = false;
} else {
this.textContent = 'Read more';
status = true;
}
});
You can use the live HTMLCollection returned by .getElementsByTagName() instead of the static NodeList returned by .querySelectorAll()
The getElementsByTagName method of Document interface returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again.
var paragraphs = document.getElementById("container").getElementsByTagName("p");
console.log(paragraphs.length);
setInterval(function() {
document.getElementById("container").insertAdjacentHTML("beforeend", "<p>p</p>");
}, 1000);
setInterval(function() {
console.log(paragraphs.length);
}, 2000);
<div id="container"></div>
Below is a really simple Snippet that demonstrates delegated events in pure Javascript, instead of using jQuery.
Here you can see I've attached the eventListener to the div with id elements, this will then listen for click events under this, a simple matches is used just in case you have other elements your not interested in..
document.querySelector("#elements").addEventListener("click", (e) => {
if (!e.target.matches('.element')) return
console.log(`Clicked ${e.target.innerText}`);
});
.element {
border: 1px solid black;
margin: 5px;
}
<div id="elements">
<div class="element">1</div>
<div class="element">2</div>
<div class="element">3</div>
<div>Clicking this does nothing.</div>
</div>

Javascript - Submit Text Field, Show Div, Hide All Others

I have a simple form (text field and submit button). I am trying to have the user submit a number, and the resulting number will display one div (from a set of divs).
I tried using this example as a base (when the user clicks a link, it shows a div, but hides others).
My test is below:
var divState = {};
function showhide(oFrm) {
var dividnum = oFrm.Inputed.value;
var prepar = "para";
var divid = prepar + theInput; /* should result in something like "para52" */
divState[divid] = (divState[divid]) ? false : true;
//close others
for (var div in divState){
if (divState[div] && div != divid){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
http://jsfiddle.net/LfzYc/431/
Note: I am NOT proficient in JavaScript at all, which is why I am having difficulty.
Also, I'd like to add a function ... if the number entered is not between 1-4, show a different div, maybe with the id paraEnd.
Please look at the jsFiddle based on your one. I hope I've done what you want. I changed the showhide function and your HTML (fixed div's IDs and added one more div#paraEnd). I'd suggest you refactoring your code.
You should use jQuery to have an easy way to manipulate the DOM.
Using jQuery I made an example for you, just change your JS and paste mine:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
// get the paragraphs
var paragraphs = $('.paragraph');
// form submit
$('#paragraphform').submit(function (e) {
// prevent the event to flow
e.preventDefault();
// get the input value
var value = $('#Inputed').val() - 1;
// reset all divs removing active css class
paragraphs.removeClass('active');
$('.error').removeClass('active');
// verify if the value doens't exist
if(value < 0 || value > paragraphs.length - 1) {
$('.error').addClass('active');
return;
}
// show the active div
paragraphs.eq(value).addClass('active');
});
})(jQuery);
</script>
Is that what you need?
If you not familiar with jQuery, this is the jquery Learn Center:
https://learn.jquery.com/
And this is a nice tutorial for beginners:
http://www.tutorialspoint.com/jquery/

Assigning .on() - keyup to dynamically created elements

The idea of this script is to allow dynamically created elements to respond to a keyup function that changes the inner html (or jQuery text()) based on what is inside of a text form.
Each dynamically created element has it's own text form and title. So whatever you type in that given element's text form should become the title for that element which is wrapped in tags.
I've tried a few ways but I just cant get it to work. What is the best way to go about this?
Here's my latest attempt - http://jsfiddle.net/gnkxxgjz/1/
$('body').on('keyup', '.qForms', function() {
var nameOfLoan = [];
var loanOfName = function(t) {
if ($(this).hasClass('.loanNameV'+t)) {
$('body').on('keyup', '.qForms', function() {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
else {
return false;
}
};
for (var t=1; t < z; t++) {
nameOfLoan[t] = loanOfName(t);
}
for (var j=1; j < z; j++) {
nameOfLoan[j]();
}
});
Take a look at this Fiddle
<button onclick="crea()">create</button>
<div id="d1">
</div>
function crea(){
$('#d1').append( $("<h2></h2><input>").on('keyup',function(){
$(this).prev().html( $(this).val() );
}) )
}
Something along these lines:
$(document).on("keypress", $("input"), function(e){
console.log($(e.target).attr("id"))
});
This will print to the console the id attribute of any input field you type into. Please provide how the input and text elements are related and I might be able to link them in this code piece.

Why isn't my div swap working?

So, I need a div to slide up when another slides down.
Example:
When Home button is clicked a div, we'll call it box_Home, slides down. When Games button is clicked, box_Home should slide up and then box_Games should slide down. What's happening is that they are overlapping instead of swapping out.
http://jsfiddle.net/M8UgQ/15/
var open = $('.open'),
a = $('ul').find('a');
console.log(a.hasClass('active'));
open.click(function(e) {
e.preventDefault();
var $this = $(this),
speed = 500;
var link_id = $this.attr('id');
var box_id = '#box_' + link_id;
console.log(box_id);
if($this.hasClass('active') === true) {
$this.removeClass('active');
$(box_id).slideUp(speed);
} else if(a.hasClass('active') === false) {
$this.addClass('active');
$(box_id).slideDown(speed);
} else {
a.removeClass('active')
$(box_id).slideUp(speed);
$this.addClass('active');
$(box_id).delay(speed).slideDown(speed);
}
});
take a look at this
http://jsfiddle.net/rWrJ9/1/
the main idea is...
if the element clicked is active, remove it, otherwise: 1. find (if any) already active elements (using $('.active')) and use jQuery.map() to make them inactive and slide them up, and 2. make the element clicked active.
I also removed the unneeded variable a
IMPORTANT: the this inside the map() function is different from the this (or rather, $this as you called it) outside the map() function
I think you're saying you have two buttons id="Home" class="open" and id="Game" class="open", and two divs id="box_Home" and id="box_Game". If so, you add class="box" to box_Home and box_Game and do something like this:
$('.open').click(function(e) {
e.preventDefault();
var $this = $(this);
var link_id = $this.attr('id');
var box_id = '#box_' + link_id;
$('.box').slideUp();
$(box_id).slideDown();
});
Hi check this fiddle i hope you need thing to implement
jsfiddle
in the if else statement you are doing a mistake
else if(a.hasClass('active') === false) {
replace it with
else if($this.hasClass('active') === false) {

Categories