--EDIT--
I have the toggle Button with which slides left and right. The toggle and animation are working fine, but the problem comes when adding more than one instance of toggle button on the same page. When I click on a toggle button, All the toggle buttons are using the same VAR. So if you open one and then click another one, the second one doesn't slide open because it thinks is suppose to close. Where would you put the isChecked var so that it is different for each instance?
js fiddle
http://jsfiddle.net/amQCN/11/
$(document).ready(function() {
var isChecked = false;
$('.toggle-radio-switch').click(function() {
if (isChecked == true) {
$(this).find('.radio-switch-slider').animate({'margin-left': '0px'},'150');
isChecked = false;
console.log("isChecked = " + isChecked);
} else {
$(this).find('.radio-switch-slider').animate({'margin-left': '34px'},'150');
isChecked = true;
console.log("isChecked = " + isChecked);
};
});
});
radio-switch-slider is positioned on top of the contents and slides back and forth revealing yes or no
<div class="toggle-radio-switch" id="toggle3">
<span>yes</span>
<span>no</span>
<div class="radio-switch-slider"></div>
</div>
Working version incase anyone is wondering:
Ended up just using this instead
$('.toggle-radio-switch').click(function() {
if ($(this).find('.radio-switch-slider').css('margin-left')=="0px"){
$(this).find('.radio-switch-slider').animate({'margin-left': '34px'},'150');
} else {
$(this).find('.radio-switch-slider').animate({'margin-left': '0px'},'150');
}
});
I'm betting your .toggle-radio-switch elements are siblings. Remove .parent() from your code. It isn't needed since .radio-switch-slider is contained directly in .toggle-radio-switch
$(this).find('.radio-switch-slider')...
Related
I have this code:
function showAll(el){
var id = el.parentNode.id;
var all= document.getElementById(id).getElementsByClassName('items')[0];
if(all.style.display === 'block'){
all.style.display = 'none';
} else{
all.style.display = 'block';
window.addEventListener('mouseup', function(e){
document.getElementById('test').innerHTML = e.target.className;
if(e.target != all){
all.style.display = 'none';
}
});
}
}
<div id="parent">
<div class="selected" onClick="showAll(this);">
</div>
<div class="items" style="display: none">
</div>
</div>
Basically what i want to achieve is: click on selected to display items which is now hidden after that if i click again on selected or if i click outside of items(a random spot on that page or even on selected) i want to be able to hide items.
The problem is that without the EventListener when i click on selected it works to display items and then if i click again on selected it works to hide items but if i click on a random spot it doesn't work to close items.
But when i add EventListener and i click on selected it works to click a random spot to close items but it doesn't work to click selected again to close items.
Can anybody help me with a full JavaScript explanation, please?
You're going to want to use highly reusable code. I use change() and id_() on my web platform all of the time and it's very direct and simple. In the below example the second parameter will make the class empty (you can also use id_('items').removeAttribute('class') for a cleaner DOM (Document Object Model)).
HTML
<input onclick="change(id_('items','');" type="button" value="Display Items" />
<div clas="hidden" id="items"><p>Items here.</p></div>
CSS
.hidden {display: none;}
JavaScript
function change(id,c)
{
if (id_(id)) {id_(id).className = c; if (id_(id).className=='') {id_(id).removeAttribute('class');}}
else if (id) {id.className = c; if (id.className=='') {id.removeAttribute('class');}}
else {alert('Error: the class id \''+id+'\' was not found or has not yet been imported to the DOM.\n\nNew class intended: '+c);}
}
function id_(id)
{
if (id == '' && window['console']) {console.log('Developer: empty id called from: '+id_.caller.toString().split('function ')[1].split('(')[0]);}
return (document.getElementById(id)) ? document.getElementById(id) : false;
}
This code exists from years of refining the same platform instead of industry standard drama of pointlessly changing things. You are two clicks from finding more highly reusable functions on my platform's JavaScript documentation from the link in my profile.
I've made a fiddle of my code (without the css styling) here: http://jsfiddle.net/X8bVr/
I'm trying to show a trash icon when a user hovers over a list input (dynamically generated from an input). Right now, the icon shows on hover, but doesn't go away on hover. Upon multiple mouseovers, it multiples the amount of icons on each list item.
I also want to make the trash icon a link that removes that specific list item.
Any other helpful tips towards optimizing my code is appreciated!
$(".input").click(function() {
if ($(this).val() == "Add task...") {
$(this).val('');
}
});
$('.input').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13' && $('.input').val().length != 0){
var input = $(".input").val();
var li = $("<li/>").text(input);
$("#tasks").prepend(li);
if ($(".input").val() != "Add task...") {
$(".input").val('');
}
$("li").hover(function() {
var trashIcon = $("<i class='fa fa-trash-o'></i>");
$(trashIcon).appendTo($(this)).stop();
}, function() {
$(trashIcon).hide();
});
}
});
Try looking mouseenter and mouseleave instead of hover:
1) Just add the icon on page load, and hide it
var trashIcon = $("<i class='fa fa-trash-o'></i>");
$(trashIcon).appendTo($(this)).stop();
$(trashIcon).hide();
2) Insted of hover, show icon when mouse enters li elements and hide when mouse gets out:
$("li").mouseenter(function() {
$(trashIcon).show();
};
$("li").mouseleave(function() {
$(trashIcon).hide();
};
This is a very small mistake.The scope of var trashIcon is only when the mouse is on the li so this is the problem.
you can fix it in two ways
make var trashIcon global variable.
to the image use following code.
$(this).find('.fa').hide();
hope this solves your problem.
Edit :
The $(trashIcon) is global hence when the next li is being appended the previous ones is being removed.
you can check it by F12 elements.
So here is the solution to your problem.
Declare the
var trashIcon = $("<i class='fa fa-trash-o'></i>");
just before you register the mouseenter and mouseleave event
Fiddle demo to explain more
I have this simple code which shows 3 items
When I press the header ($(".fileHeader")) , it should open then next element which is the next element (hidden div) ($(".LST_Documents"))
sketch :
JSBIN : it does work.
Most important :
When I press on a $(".fileHeader")- i need to close all other $(".LST_Documents") and then ( that why i used promise) open the relevant $(".LST_Documents").
The problem is (look at the pic) if i press again on the first $(".fileHeader").
what is happening is that it closing and then re opening. and I want it to stay CLOSED.
P.S.
I could solve it with class ( .rowOpen or something like that) but I want to do it via JS/JQ only.
How can I enhance my code to work as expected ?
Just hold the header's content visibility state before sliding it up. And slide down the content only when it was not visible.
Here is the fiddle.
$(".fileHeader").on('click', function () {
var content$ = $(this).next(),
isContentVisible = content$.is(':visible');
$(".LST_Documents:visible").slideUp().promise().done(function () {
if ( ! isContentVisible ) {
content$.slideDown();
}
});
});
How 'bout a simple condition:
$(".fileheader").on('click', function() {
var next = $(this).next();
if(next.is(':visible'))
{
next.slideUp();
}
else
{
$(".LST_Documents:visible").slideUp().promise().done(function() {
next.slideDown();
});
}
});
I'm helping my friend Michaela out for our web design class. She did the HTML, and I've changed just a few of the lines and added some divs. She wants it so if the user clicks on a radio button then the corresponding div is shown. All div's for her form start out hidden in a class "hidden_destiny". -- This going to be a series of nested div's and I may need to change the layout later.
Here's the JsFiddle.
Here's my javascript:
if ($('#radio_starwars').is(':checked')){
$('#clicked_starwars').hide().slideDown('slow');
$('.hidden_destiny').not('#clicked_starwars').hide().slideUp('slow');
}
else if ($('#radio_avengers').attr('checked', 'true')){}
else if ($('#radio_batman').attr('checked', 'true')){}
else if ($('#radio_xmen').attr('checked', 'true')){}
else if ($('#radio_harryp').attr('checked', 'true')){}
else if ($('#radio_lotr').attr('checked', 'true')){}
[EDIT] Updated code. Add id identifier to code and updated JsFiddle link.
Try this code:
$(":radio").change(function(){
$(".hidden_destiny").hide()//hide divs
$("#clicked_"+this.id.replace("radio_","")).show()//show div by radio id
})
http://jsfiddle.net/YZ9fh/
$('.fate').click(function () {
$('.hidden_destiny').each(function () {
if ($(this).is(':visible')) {
$(this).slideUp('slow');
}
});
var id = $(this).val();
$('#clicked_' + id).slideDown('slow');
});
jsfiddle
What I am trying to achieve here is when a user clicks an element it becomes hidden, once this happens I want to prepend inside the containing element another Element to make all these items visible again.
var checkIfleft = $('#left .module'),checkIfright = $('#right .module');
if(checkIfleft.hasClass('hidden')) {
$('#left').prepend('<span class="resetLeft">Reset Left</span>');
} else if(checkIfright.hasClass('hidden')) {
right.prepend('<span class="resetRight">Reset Right</span>');
}
I tried multiple ways, and honestly I believe .length ==1 would be my best bet, because I only want one element to be prepended. I believe the above JS I have will prepend a new element each time a new item is hidden if it worked.
Other Try:
var checkIfleft = $('#left .module').hasClass('hidden'),
checkIfright = $('#right .module').hasClass('hidden');
if(checkIfleft.length== 1) {
$('#left').prepend('<span class="resetLeft">Reset Left</span>');
} else if(checkIfright.length== 1) {
right.prepend('<span class="resetRight">Reset Right</span>');
}
else if(checkIfleft.length==0){
$('.resetLeft').remove()
} else if (checkIfright.length==0){
$('.resetRight').remove()
}
Basically if one element inside the container is hidden I want a reset button to appear, if not remove that reset button...
hasClass() only works on the first item in the collection so it isn't doing what you want. It won't tell you if any item has that class.
You can do something like this instead where you count how many hidden items there are and if there are 1 or more and there isn't already a reset button, then you add the reset button. If there are no hidden items and there is a reset button, you remove it:
function checkResetButtons() {
var resetLeft = $('#left .resetLeft').length === 0;
var resetRight = $('#left .resetRight').length === 0;
var leftHidden = $('#left .module .hidden').length !== 0;
var rightHidden = $('#right .module .hidden').length !== 0;
if (leftHidden && !resetLeft) {
// make sure a button is added if needed and not already present
$('#left').prepend('<span class="resetLeft">Reset Left</span>');
} else if (!leftHidden) {
// make sure button is removed if no hidden items
// if no button exists, this just does nothing
$('#left .resetLeft').remove();
}
if (rightHidden && !resetRight) {
$('#right').prepend('<span class="resetRight">Reset Right</span>');
} else if (!rightHidden) {
$('#right .resetRight').remove();
}
}
// event handlers for the reset buttons
// uses delegated event handling so it will work even though the reset buttons
// are deleted and recreated
$("#left").on("click", ".resetLeft", function() {
$("#left .hidden").removeClass("hidden");
$("#left .resetLeft").remove();
});
$("#right").on("click", ".resetRight", function() {
$("#right .hidden").removeClass("hidden");
$("#right .resetRight").remove();
});
FYI, if we could change the HTML to use more common classes, the separate code for left and right could be combined into one piece of common code.
Add the reset button when hiding the .module, if it's not already there :
$('#left .module').on('click', function() {
$(this).addClass('hidden');
var parent = $(this).closest('#left');
if ( ! parent.find('.resetLeft') ) {
var res = $('<span />', {'class': 'resetLeft', text : 'Reset Left'});
parent.append(res);
res.one('click', function() {
$(this).closest('#left').find('.module').show();
$(this).remove();
});
}
});
repeat for right side !
I've recently experimented with using CSS to do some of this stuff and I feel that it works quite well if you're not trying to animate it. Here is a jsfiddle where I can hide a module and show the reset button in one go by adding/removing a 'hideLeft' or 'hideRight' class to the common parent of the two modules.
It works by hiding both reset button divs at first. Then it uses .hideLeft #left { display:none;} and .hideLeft #right .resetLeft { display: block; } to hide the left module and display the reset button when .hideLeft has been added to whichever element both elements descend from. I was inspired by modernizr a while back and thought it was a neat alternative way to do things. Let me know what you think, if you find it helpful, and if you have any questions :)