Javascript - Click Button to FadeIn, FadeOut by clicking anywhere - javascript

I want my navigation to fade-in when a special button is clicked, and to fade away when the user is clicking somewhere else - doesn't matter where.
My Script looks like this:
function showText() {
var spoiler = document.getElementById('spoiler');
var button = document.getElementById('navicon');
if (spoiler.style.display == 'block') {
spoiler.style.display='none';
button.value = 'Text einblenden';
} else {
spoiler.style.display='block';
button.value = 'Text ausblenden';
}
return false;
}
My workaround was to give every navigation element the following code snippet.
onclick="$('#thedivlayeriwanttofadeout').fadeOut('slow');"
Can anybody help me?

Use bubbling to attach a single click handler to a common parent element (for example, body).
Here's a simple example:
$(function () {
$("#myButton").click(function (e) {
$("#hidden").fadeIn();
return false;
});
$("#parent").click(function() {
$("#hidden").fadeOut();
});
});
Clicking the button will fade in the element with id hidden. Clicking anywhere in parent will fade it out again.

Related

How to make an action on first click and another action on second click

My goal is to move a div element to the right side of the page on the first click and move it back to the left if I click it again and so on. How can I do this in javascript?
As enhzfelp said in their comment, the best solution would be to create a css class which moves your element to the right side of the page and to add / remove it with javascript.
If your goal is actually to perform one action and on next event call perform another, you can simply change a variable whenever the event is called.
Example code:
let right = false;
someElement.on('click', () => {
right = !right;
if (right) moveRight();
else moveLeft();
});
function moveRight() { ... }
function moveLeft() { ... }
You can also do this
<script>
var clickCount = 0;
function checkClick() {
if ( clickCount % 2 == 0 ) {
alert("first click");
} else {
alert("Second click");
}
clickCount++
}
</script>
<button onclick="checkClick()">Click me</button>
So, as I understood, you want to make so on click, the div element move to the opositive direction of left or right.
You can make this with an event listener, that listens to the click event and execute whatever you want on every click.
document.addEventListener('click', function(event) {
// your code that executes on every click
});
This event listener listens the click on all your webpage, so if you want to only listen the click when the use click your div, you need to get the div. There are several ways, but I recomend you to add an id to the div.
<div id="iAmYourElement"></div>
And then get the element in JavaScript
const element = document.getElementById("iAmYourElement");
element.addEventListener('click', function(event) {
// your code that executes on every click
});
Now that we have the way to deal with the click event, let's talk about the code that goes inside the listener.
One way to do this is creating two CSS classes, one is your div on the left and another whe div on your right. So, if we need the element to be on the right, we add the right-class, and if we need the div to be to the left, we add left-class and remove right-class.
Final javascript code will looks like that:
const element = document.getElementById("iAmYourElement");
let isDivOnLeft = true;
element.addEventListener('click', function (event) { // executes if you click on the div
isDivOnLeft = !isDivOnLeft // We negate the value of isDivOnLeft, so if it was true, it will now be false and vice versa.
if (isDivOnLeft) {
elementToRight()
} else {
elementToLeft()
}
});
function elementToRight() {
element.classList.remove("left-class")
element.classList.add("right-class")
}
function elementToLeft() {
element.classList.remove("right-class")
element.classList.add("left-class")
}
Hmm,
my English is kinda weak so I'll try my best to explain.
Let's assume that we have a div with id moveable
<div id="moveable"></div>
And we have button
<button id="move">Move</div>
And our goal is to move the div to the right in the first click, and in the second click, we will move it back to the right.
let button = document.getElementById("move");
let div = document.getElementById("moveable");
button.addEventListener("click", function () {
const dataMovedAttribute = div.getAttribute("data-moved");
if (dataMovedAttribute && dataMovedAttribute === "true") {
div.setAttribute("data-moved", "false");
div.style.float = "left";
} else {
div.setAttribute("data-moved", "true");
div.style.float = "right";
}
});
Checkout this example:
https://codesandbox.io/s/vigilant-rosalind-176by

Logic for showing elements and hiding them on body click

I have some piece of code.
This code on button click open menu.
When i click on button again, menu is hidden (i remove .show class, show class has display:block rule, so i toggle visibility of this item by clicking on button).
In next line, i have event, which check what element is clicked. If i "click" outside" of menu, menu become hidden, beacuse i remove .show class.
And now i have a problem, it looks like first part of code dont work anymore (button.on('click')) - i mean, work, but second part of code is also executed, and this logic is now broken.
Have you got any idea for workaround?
Thanks
var menu = $('.main-menu');
var button = $('.burger');
button.on('click',function() {
if (menu.hasClass('show')) {
menu.removeClass('show');
$(this).removeClass('opened');
} else {
menu.addClass('show');
$(this).addClass('opened');
}
});
$(document).bind( "mouseup touchend", function(e){
var container = menu;
if (!container.is(e.target)
&& container.has(e.target).length === 0) {
container.removeClass('show');
button.removeClass('opened');
}
});
maybe use jQuery toggle() method ? For example:
button.on('click',function() {
menu.toggle();
});
You need to bind an outer click event only when the button click event has been triggered, and remove the outer click event when the outer click event has been triggered:
var menu = $('.main-menu');
var button = $('.burger');
button.on('click',function() {
if (menu.hasClass('show')) {
menu.removeClass('show');
$(this).removeClass('opened');
} else {
menu.addClass('show');
$(this).addClass('opened');
}
var butbindfunc = function(e){
var container = menu;
container.removeClass('show');
button.removeClass('opened');
$(this).unbind("mouseup touchend", butbindfunc);
};
$(document).not(button).bind( "mouseup touchend", butbindfunc);
});
Note, that I have removed your condition in the document binding callback, and simple excluded it from the select set.

Show a Div first and then Submit on second click of button in a form

I have a form with multiple divs with same names (full-width). They all are on the same level. One of them is hidden (with a class hide). What I want is that if I select Submit, it should not submit, first hide all the brother divs of the hidden div (in this case full-width) and unhide the one with the class hide.
Now when I press again, it should just submit the Form.
JSFiddle is here:- http://jsfiddle.net/xmqvx/2/
Your code had a couple issues:
You used event.preventDefault but passed event in as e - should be e.preventDefault
Your ID selector targeted an ID that didnt exist (changed to #submit-this)
The working code:
$("#submit-this").click(function (e) {
e.preventDefault();
if ($(".full-width").hasClass("hide")) {
$(".full-width").hide();
$(".full-width.hide").removeClass("hide").show();
} else {
alert("Submitting");
$("#this-form").submit();
}
});
http://jsfiddle.net/xmqvx/4/
You could also take advantage of JavaScript's closures like so, to avoid having your behavior be dependent on your UI:
$(document).ready(function () {
var alreadyClicked = false;
$("#submit-this").click(function (e) {
e.preventDefault();
if (alreadyClicked) {
$('#this-form').submit();
} else {
$('.full-width').hide();
$('.hide').show();
alreadyClicked = true;
}
});
});

Popovers not showing up on first click but show up on second click

I found a related post which did not help:
Twitter bootstrap:Popovers are not showing up on first click but show up on second click
The difference is in my page I have several elements which require popover (several tips-icon), so I need to loop over them..
My markup:
<img class="help_icon" src="http://media.mysite.com/pub/images/help/tips-icon.png">
This is my javascript:
var h=document.getElementsByName("click_help_container");
for (i=0;i<h.length;i++)
{
$('#'+h[i]['id']).click(
function ()
{
var id=$(this).attr("id");
getHelp(id,$(this),function(t,elem)
{
var isVisible = false;
var clickedAway = false;
$(elem).unbind('click');
$(elem).popover(
{
"title":t.title,
"content":"<p class='popover_body_text'>"+t.content+"</p>",
"html":true,
"animation":true,
"placement":"bottom",
"trigger":"manual"
}).click(function(e)
{
$(this).popover('show');
clickedAway = false;
isVisible = true;
e.preventDefault();
});
$(document).click(function(e) {
if(isVisible & clickedAway)
{
$(elem).popover('hide')
isVisible = false;
clickedAway = false;
}else
{
clickedAway = true;
}
});
//$(elem).popover('show');
});
});
}
The problem is when I click on the tips-icon.png button, the popover doesn't show up on first click (I guess it's because I have 2 .click() calls When I click on the button the second time popover shows up and it then maintains it's toggle behavior from there onwards.
You don't need to loop through all elements and initialize popovers one by one, you can apply popover to all items with this name at once (same as you're doing in loop).
And you don't need to show/hide popovers manually by yourself, bootstrap can do it for you.
I think this should work for you:
$("a[name='click_help_container']").popover(
{
"title":t.title,
"content":"<p class='popover_body_text'>"+t.content+"</p>",
"html":true,
"animation":true,
"placement":"bottom",
"trigger":"click"
});

Toggle event capturing in jQuery or Javascript?

I have elements on my page (id=itemid) that when hovered over cause another element (id=panel) to become visible (via fadeIn). Basically a hover event on itemid causes panel to fadeIn and mouseOut leads to fadeOut.
I want to make a button so that when clicked the panel element does not fadeIn or out but stays visible. When that button is clicked, the mouseIn and mouseOut events should work again.
Any ideas?
Thank you!
$(document).ready(function(){
$('.itemid').hover(
function () {
$('.panel').fadeIn(300);
},
function () {
$('.panel').fadeOut(200);
}
);
});
Set a flag for whether to do the fading or not:
$(document).ready(function(){
var fadeEnabled = true;
$('.itemid').hover(
function () {
if (fadeEnabled) {
$('.panel').fadeIn(300);
}
},
function () {
if (fadeEnabled) {
$('.panel').fadeOut(200);
}
}
);
$("#myButton").click(function() {
fadeEnabled = !fadeEnabled;
});
});
Then, just toggle that flag with your button and it will enable or disable the fade behavior.
On click of the button, use $(selector).unbind('mousein') on your object/item to deregister the events., and the reregister on another click of the button. Keep toggling on each click of the button.

Categories

Resources