How can I have elements .show in the order they're clicked and not the order they're appear in the HTML using jquery?
E.g.
Css code:
.sq{
display:none;
}
Html Code:
A
B
C
<span class="sq" id="01">a</span>
<span class="sq" id="02">b</span>
<span class="sq" id="03">c</span>
JavaScript code:
$("#1").click(function(){
$("#01").show();
});
$("#2").click(function(){
$("#02").show();
});
$("#3").click(function(){
$("#03").show();
});
Using this code if I click C,B,A the output will arrange "a b c"
What I would like is if I click C,B,A the output should arrange "c b a"
I've tried various CSS positioning rules to do this, but the best I can do is have them arrange in the same position as each other. I realize I could make a new class for each but would rather not do it that way in the interest of minimal code and I'm learning right now so it would be useful to know a better way around the issue.
Here's a fiddle: http://jsfiddle.net/xuxsuagg/4/
You can do something like
$(".myclass").one('click', function() {
$($(this).data('target')).appendTo('.output').show();
});
a {
text-decoration: none;
}
.sq {
display: none;
}
.output {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
A
B
C
D
E
F
<p class="output">
<span class="sq" id="01">A</span>
<span class="sq" id="02">B</span>
<span class="sq" id="03">C</span>
<span class="sq" id="04">D</span>
<span class="sq" id="05">E</span>
<span class="sq" id="06">F</span>
</p>
Notes
Used a common event handler instead of using different handlers for each link
Before shown the element the target is moved to the last position of the parent
Used .one() to register the handler so that one element is shown only once
There is a very simple trick: use .append(). When you append a selected element that is already present in the DOM, you are actually moving it around. Also, I recommend that to optimize your code, you can:
Use a common class for the <a> elements
Assigned a HTML5 data- attribute, say data-target, to specify the ID of its intended target
Listen to click events triggered on the common class
An example of the proposed new markup:
A
B
<!-- and more -->
Here is the code (and the demo fiddle here—http://jsfiddle.net/teddyrised/xuxsuagg/9/)
$('.sq-click').click(function(e) {
// Prevent default action
e.preventDefault();
// Use .append() to move element
var $out = $('.output');
$out.find('#'+$(this).attr('data-target')).appendTo($out).show();
});
On a side note, if you do not want the users to rearrange the order after an anchor has been clicked, you will have to rely on the .one() method for listening to click events. Also, it will help that you style the disabled anchors appropriately so the users can see it—see proof-of-concept demo: http://jsfiddle.net/teddyrised/xuxsuagg/26/
$('.sq-click').one('click', function(e) {
// Prevent default action
e.preventDefault();
// Use .append() to move element
var $out = $('.output');
$out.find('#'+$(this).attr('data-target')).appendTo($out).show();
// Add class to change appearance of disabled <a>
$(this).addClass('disabled');
});
And your CSS can look like this:
.disabled {
cursor: default;
opacity: 0.2;
}
You can simplify this code to:
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
a {
text-decoration: none;
}
.sq {
display: none;
}
A
B
C
D
E
F
<p class="output">
</p>
Bind the click event to the class that they share and not their own unique id.
In the function scope of clickClosure 'this' is referring to the current element.
$(".sq").click(function clickClosure(){
$(this).show();
});
Using styles to achieve this might range from painful to very hard, depending on the exact way you want them displayed. I'd suggest instead to re-order them in DOM. That might look something like this:
<a id="link-1">...</a>
...
<div style="display: none" id="hidden-items">
<span id="item-1">...</span>
</div>
<div id="visible-items"></div>
&
$('#link-1').click(function () {
$('#visible-items').append($('#item-1'));
});
As other respondents suggested, you could also optimize your code in various ways, but that's outside the scope of the question.
Try this: You can put empty <p class="output"> and remove display:none; from CSS .sq{... In jQuery, create a <span> on the basis of clicked link and append it to <p class="output">
HTML:
A
B
C
D
E
F
<p class="output">
</p>
CSS:
.sq{
/*display:none;*/
color: green;
margin-right: 10px;
}
jQuery
$("a[href='#']").click(function(e){
e.preventDefault();
var text = '<span class="sq" id="0'+$(this).prop('id')+'">'
+$(this).text()+'</span>';
$(text).appendTo('p.output');
});
DEMO
Related
I need to remove a HTML section using a button. The button is in the HTML section I want to remove. And the section I want to remove was previously added by a button.
With Add section button I add a section below the first section, but I can't create a function to remove a section, I can't select the section I want to remove.
image of web
You're able to use the remove() method in order to do that.
Example:
HTML:
<div id="testID">your stuff.</div>
<button onclick="deleteDiv()">Delete</button>
JS:
function deleteDiv() {
var selectedDiv = document.getElementById("testID");
selectedDiv.remove();
}
try this code:-
<p id ="remove" style = "color: green; font-size: 24px; font-weight: bold;">
on click remove this section
</p>
<button onClick = "remove()">
click here
</button>
var htmlElement = document.getElementById('remove'); //use getElemeyId or getElementsByClassName According to your need;
function remove() {
htmlElement.remove();
}
I am trying to remove a class and add a class within one function. But when I click on the button nothing is happening.
This is my code
function unlikeVerhaal(unlike) {
unlike.preventDefault;
document.querySelector('#unliked').classList.add('onzichtbaar');
document.querySelector('#liked').classList.remove('onzichtbaar');
}
document.querySelector('.likebutton').addEventListener('submit', unlikeVerhaal);
.onzichtbaar {
display: none;
}
<li>
<button type="submit" class="likebutton">
<img src="icons/lined.png" alt="lined heart" class="unliked" id="unliked">
<img src="icons/solid.png" alt="solid heart" id="liked" class="onzichtbaar">
</button> 777
</li>
What I am trying to get is that the class is added to the first image and removed by the second image.
You just need to use a combination of the three methods .contains(), .add() and .remove() from the element.classList property along with a simple if/else statement (or a ternary operator if you prefer that) as can be seen in the Code Snippet below:
var btn = document.querySelector('.likebutton');
function unlikeVerhaal() {
var ul = document.getElementById("unliked");
var l = document.getElementById("liked");
if (ul.classList.contains("onzichtbaar")) {
ul.classList.remove("onzichtbaar");
l.classList.add("onzichtbaar");
console.log("Inspect your elements to see the class switching!")
} else {
l.classList.remove("onzichtbaar");
ul.classList.add("onzichtbaar");
console.log("Inspect your elements to see the class switching!")
}
}
btn.addEventListener("click", unlikeVerhaal)
.onzichtbaar {background-color: green;}
<li>
<button type="button" class="likebutton">
<div class="unliked" id="unliked">A</div>
<div id="liked" class="onzichtbaar">B</div>
</button> 777
</li>
You can either inspect the elements to see the class switching between the two or you can just watch the green background styling which is applied to an element with the onzichtbaar class name switching between the two.
This will works as you expect:
function unlikeVerhaal(e) {
e.preventDefault;
document.getElementById('unliked').classList.add('onzichtbaar');
document.getElementById('liked').classList.remove('onzichtbaar');
}
document.getElementById('likebutton').addEventListener('click', unlikeVerhaal);
Just change submit to click and remove type from button
Fiddle
Update:
Updated fiddle
I have a trigger element and a responding element.
<div class="more"></div>
<div class="info"></div>
I would like to bind an open/close type event.
$('.more').delegate($('.more'), 'click', function(){
$(this).removeClass('more');
$(this).addClass('less');
$(this).text("less...");
$('.info').addClass("open");
});
$('.less').delegate($('.less'), 'click', function(){
$(this).addClass('more');
$(this).removeClass('less');
$(this).text("more...");
$('.info').removeClass("open");
});
It doesn't work as intended, if the second function is nested in the first then you can open and close only once.
If the script is formatted sensibly as above it will open but not close.
Could anyone help me out?
Bonus if the script could support the .info could be either a sibling or the element immediately following $(.more/.less)'s parent.
I've been toying with .on/.live/.bind but less successfully than above.
Use event delegation ,and binded to document or immediate parent,not same element
$(document).on( 'click',".more", function(){
$(this).removeClass('more');
$(this).addClass('less');
$(this).text("less...");
$('.info').addClass("open");
});
$(document).on('click',".less", function(){
$(this).addClass('more');
$(this).removeClass('less');
$(this).text("more...");
$('.info').removeClass("open");
});
DEMO
NOTE: delegate was outdated with latest version of jquery ,so use on instead,
ISSUE: you are delegated with same element $('.less'),$('.more') use immediate parent or document
Just use JavaScript to toggle a class, and let CSS magic do the rest. Here is a demo: http://jsfiddle.net/pomeh/69sX5/1/
And here is the code:
HTML
<div>
Some visible content
</div>
<div class="content-fold">
<div class="more">More...</div>
<div class="less">Less...</div>
</div>
<div class="info">Some hidden additional content</div>
CSS
/* Additional content and Less button hidden by default */
.content-fold + .info, .content-fold .less {
display: none;
}
/* Additional content and Less button shown when class shown is active */
.content-fold.shown + .info, .content-fold.shown .less {
display: block;
}
/* More button hidden when additional content is shown */
.content-fold.shown .more {
display: none;
}
/*
You can also move the "div.info" into the "div.content-fold",
and use ".content-fold.shown > .info" instead of ".content-fold.shown + .info"
Browser support is quite good for adjacent selector (see http://www.quirksmode.org/css/selectors/#t11 and https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors#Browser_compatibility)
*/
JavaScript
$('.content-fold').on('click', function(){
$(this).toggleClass('shown');
});
Use id to do your task. it's easy.
Html
<div class="more" id="toggle"></div>
<div class="info"></div>
Jquery
$('#toggle').click(function(){
var $this = $(this) //store object
if($this.hasClass('more')) {
$this.removeClass('more').addClass('less').text('Less...')
$this.next('.info').addClass('open');
} else {
$this.removeClass('less').addClass('more').text('More...')
$this.next('.info').removeClass('open');
}
});
js Fiddle: http://jsfiddle.net/5N6TL/53/
This question already has answers here:
How to display one div and hide all others
(7 answers)
Closed 10 years ago.
I have four button and four div above it.
I want to only one div at time , but keep showed the four button.
Here it is the html for buttons
HTML
<div id="container">
<a><p id="firstBtn" class="mediabutton"><span class="icon"></span>button1</p></a> <!-- 1st button -->
<div id="firstDiv" class="mediaoptions" >
... <!-- stuff of the div -->
</div>
<a><p id="sndBtn" class="mediabutton active"><span class="icon"></span>button2</p></a> <!-- 2st button -->
<div id="sndDiv" class="mediaoptions" >
... <!-- stuff of the div -->
</div>
This is how I can recogniz which button was clicked
Javascript
$("container").click(function(event){
var that = event.target.id;
if(((that == "firstBtn") || (that == "sndBtn") || (that == "trdBtn") || (that == "fourBtn") )
&& !($("#"+that).hasClass("active"))
)
{
//Here comes the stuff
}
});
Now. The active class let the button to be Highlighted. I want only one button highlight.
The sndDiv is set on display : block , the others are set on display: none.
Making a recap : I want to press a button , show the div above it and hide everybody else. I tried really a lot of stuff, but i failed.
Sorry for my english, Cheers.
Just replace Btn with Div, and you have the element you'd like to show, the others have a common class and are easy to target :
$("#container").on('click', '.mediabutton', function(event){
var that = event.target.id,
elem = $('#' + that.replace('Btn','Div'));
if( !$("#"+that).hasClass("active") ) {
$('.mediaoptions').not(elem).hide();
elem.show()
}
});
The following should work.
$("container").click(function(event){
var that = event.target.id;
if(((that == "firstBtn") || (that == "sndBtn") || (that == "trdBtn") || (that == "fourBtn") ) && !($("#"+that).hasClass("active")))
{
$('.mediaoptions').show();
$('#'+that.replace('Btn','Div')).show();
}
});
I hate to just point you to a link, but I created a really lightweight jQuery script to handle stuff like this that you might found useful: http://cferdinandi.github.com/tabby/.
You may find it easier to just repurpose that than try to modify your existing code to work.
Don't jQuery .hide() and .show() do the job?
http://api.jquery.com/hide/
Add the second line below to your javascript and see what is alerted:
var that = event.target.id;
alert(that);
I'm not sure exactly what you're trying to accomplish perhaps something like:
<p id="sndBtn" class="mediabutton active"><span class="icon"></span>button2</p>
See this example: JsFiddle. I made some updates on javascript and html;
$(".mediabutton").click(function(event){
$(".mediabutton").removeClass("active");
$(this).addClass("active");
$(".mediaoptions").hide();
$("#"+$(this).data("target-div")).show();
});
Here is the working jsFiddle: http://jsfiddle.net/CtqUU/
With this you can have as many <div> and <button> elements as you want. Change class names and id as needed to fit what you need.
HTML:
<div class="hidden" id="box1">Box 1</div>
<button value="box1">Box 1</button>
<div class="hidden" id="box2">Box 2</div>
<button value="box2">Box 2</button>
CSS:
div {
width: 200px;
height: 200px;
border: 1px solid #000000;
}
.hidden {
display: none;
visibility: hidden;
}
JS:
$("button").click(function(){
var val = $(this).val();
$("div").addClass("hidden");
$("#"+val).removeClass("hidden");
});
I have h3 block's and on click of each of the block I am showing the section associated with it. It is actually something like accordion(hide and collapse). I have also given a drop icon to the h3 tags, means that when the block is opened the h3 should have a dropicon pointing downwards while others h3 should have there dropocons towards right. I am controlling this behaviour using backgroundPosition. I am using the jQuery visible condition to see if the particular block is visible then give its drop icon one background position and to the rest other. It works fine but only for first click. It doesn't work for second click; can somebody explain why? Here is my code:
if($(this).next().is(':visible')) {
$(this).css({'backgroundPosition':'0px 14px'});
}
else {
$("h3").css({'backgroundPosition':'0px -11px'});
}
UPDATED CODE:
$("h3").click(function() {
$(".tabs").hide();
$(this).next().show();
if($(this).next().is(':visible')) {
$(this).css({'backgroundPosition':'0px 14px'});
} else {
$("h3").css({'backgroundPosition':'0px -11px'});
}
})
If you wrap the whole block in a div it might make traversing easier.
Html:
<div class="drop-block">
<h3>Click this</h3>
<ul>
<li>Drop</li>
<li>it</li>
<li>like</li>
<li>it's</li>
<li>hot</li>
</ul>
</div>
Jquery:
var dropper = $('.drop-block');
$(dropper).find('h3').click(function(){
$(this).toggleClass('active');
$(dropper).find('ul').toggle();
});
Example
I Belive that you are looking for live
So it will be something like this:
$(element).live('click', function(){
if($(this).next().is(':visible')) {
$(this).css({'backgroundPosition':'0px 14px'});
}
else {
$("h3").css({'backgroundPosition':'0px -11px'});
}
}
Instead of editing the css of them, make a css class "open" (or similar), and then add / remove the class on the click to open / close.
It is much easier to debug by checking for the existence of a class than it is to check the css properties of something in JS.
Better make a class name for each situation and easly handle the action
$('h3').on('click', function(){
if($(this).hasClass('opened')) {
$(this).removeClass('opened');
}
else {
$(this).addClass('opened');
}
}
$(document).on('click', 'h3', function(e) {
$(".tabs").hide('slow');
$(this).css({'backgroundPosition':'0px 14px'});
if(!$(this).next().is(':visible'))
{
$("h3").css({'backgroundPosition':'0px -11px'});
$(this).next().show('slow');
}
});
You can remove 'slow' from show/hide if animation is not required
Here is an example.
It sounds like you need to bind click events to the h3 elements and toggle the visibility of the child elements:
$(function(){
$("h3").click(function(){
$(this).next(".tabs").toggle();
});
});
Example markup:
<h3>Item 1</h3>
<div class="tabs">
<h4>Option 1</h4>
<h4>Option 2</h4>
</div>
<h3>Item 2</h3>
<div class="tabs">
<h4>Option 1</h4>
<h4>Option 2</h4>
</div>
Here's a jsFiddle to demonstrate.