Javascript when button onclick change element position - javascript

I'm trying to do a button that when clicked will change my div position, I already do this:
function myFunctionkomp1()
{
document.getElementsByClassName("MyDiv")[0].style.top="300px";
}
<button onclick="myFunctionkomp1();" id="btnmenukomp"></button>
<div class="MyDiv" style="position: relative;"></div>
And it works, but the only problem is that when I will click a second time on it the margin top will go to 0 (default).
Can someone please help me ?

function myFunctionkomp1()
{
if(document.getElementsByClassName("MyDiv")[0].style.top == '300px'){
document.getElementsByClassName("MyDiv")[0].style.top="0px";
}else{
document.getElementsByClassName("MyDiv")[0].style.top="300px";
}
}

I won't give you the code of how to do it, but a good approach would be to do a "toggle" that alters between top=0px and top=300px. That way the 1st click with go to top =300px, 2nd click will go to top=0px, 3rd click will go back to 300px, etc.

Add some kind of toggle functionality. Eg:
var top = document.getElementsByClassName("MyDiv")[0].style.top;
top = top === '300px' ? 0 : '300px';
document.getElementsByClassName("MyDiv")[0].style.top = top;
Here is a fiddle: https://jsfiddle.net/ubL3hx2w/

You need a toggle variable like this (there are shorter ways to do this but in order to illustrate what the code is doing I have written it this way:
<script>
var toggle=true;
function myFunctionkomp1()
{
if(flip) {
document.getElementsByClassName("MyDiv")[0].style.top="300px";
toggle=false;
}
else {
document.getElementsByClassName("MyDiv")[0].style.marginTop="0px";
toggle=true;
}
}
</script>

Related

Poweroff toggle button/div

I’m trying to make a power off button (actually it is a div), that when I click, it will change its appearance.
It looks like an interruptor, so I want to change the background-color of the page, the color of the icon ‘power off’ and the border-style of the button.
I took this function from another site and it is doing well in adding once a CSS property, but I want it to go on and of always.
document.getElementById('io').addEventListener('click', function () {
if (this.classList.contains('poweroff')) {
// this.classList.remove('poweroff');
this.classList.add('on');
} else {
this.classList.remove('on');
}
});
I believe the logic will be something like
x = x - 1
where x need to go turning from 0 to 1 and from 1 to 0, every time I click the button.
<body>
<div class="interruptor">
<div id="io" class="poweroff">
<i class="fa fa-power-off"></i>
</div>
</div>
<script src="https://use.fontawesome.com/ddde7c70b6.js"></script>
<script src="/js/logic.js" charset="utf-8"> </script>
</body>
Since you are checking on the basis of powerOff class you need to toggle it also like this
document.getElementById('io').addEventListener('click', function () {
if (this.classList.contains('poweroff')) {
this.classList.remove('poweroff');
this.classList.add('on');
} else {
this.classList.add('poweroff');
this.classList.remove('on');
}
});
Instead of checking if condition and adding and removing classes, use toggle like this
Read Here about toggle
document.getElementById('io').addEventListener('click', function () {
this.classList.toggle('on');
});
You should use toggle instead of add and remove, as :
document.getElementById('io').addEventListener('click', function () {
if (this.classList.contains('poweroff')) {
this.classList.toggle('poweroff');
this.classList.toggle('on');
} else {
this.classList.toggle('on');
}
});
This way it will automatically add and remove class on button click.

Add class on div mouse enter mouse leave and click

What i am trying to achieve is, i want to make it work like star rating. When you enter mouse star becomes yellow, when you leave mouse it turns gray and then if you click it again becomes yellow.
Not getting how to achieve it, I have added code to show you what i have tried so far.
JSfiddle
$(".na").hover(
function () {
$(this).addClass("clickstar");
},
function () {
$(this).removeClass("clickstar");
}
);
$(".na").on("click",function(){
$(this).toggleClass("clickstar");
});
.clickstar{
background: #00A1EF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="na" style="border:1px solid #c0c0c0;border-radius:50%;width:115px;height:115px;display:inline-table;margin-right:5px;"></div>
You should consider using 2 different classes, .hoverstar and .clickstar, then :
http://jsfiddle.net/xLxbw216/1/
You would have one class for each case, which seems more logical ?
You can also make it simpler by removing .hover() method, and do it with CSS :
http://jsfiddle.net/xLxbw216/8/
I probably choose the second one, even if the first solution seems to be more "readable".
You can do it like this:
$(".na").on("click",function(){
$(this).toggleClass("clickstar");
});
Fiddle Example
You should use a different class for permanent start and hover star
I have created a working example in JSfiddle
$(".na").hover(
function () {
var $this = $(this);
if (!$this.hasClass("permstar")) {
$this.addClass("clickstar");
}
},
function () {
var $this = $(this);
if (!$this.hasClass("permstar")) {
$(this).removeClass("clickstar");
}
}
);
$(".na").on("click",function(){
$(this).toggleClass("permstar");
});
add/remove class on hover events was conflicting with on click event, so i have moved the hover functionality to css
css:
.clickstar{
background: #00A1EF;
}
.na:hover{
background: #00A1EF;
}
live demo:
http://jsfiddle.net/dreamweiver/xLxbw216/7/
Happy Coding :)

hide one div when another is showing in jQuery?

I am trying to hide a div when another one is visible.
I have div 1 and div 2.
If div 2 is showing then div 1 should hide and if div 2 is not showing then div 1 should be visible/unhide.
The function would need to be function/document ready upon page load.
I've tried this but I'm not having any luck, can someone please show me how I can do this.
<script>
window.onLoad(function () {
if ($('.div2').is(":visible")) {
$(".div1").fadeOut(fast);
} else if ($('.div2').is(":hidden")) {
$('.div1').fadeIn(fast);
}
});
</script>
Add a class of hidden to each div, then toggle between that class using jQuery. By the way, window.onload is not a function, it expects a string like window.onload = function() {}. Also, put fast in quotations. I don't know if that's required, but that's how jQuery says to do it.
<div class="div1"></div>
<div class="div2 hidden"></div>
.hidden { display: none }
$(document).ready(function() {
if($(".div1").hasClass("hidden")) {
$(".div2").fadeIn("fast");
}
else if($(".div2").hasClass("hidden")) {
$(".div1").fadeIn("fast");
}
});
You should pass a string to the .fadeIn() and .fadeOut() methods.
Instead of .fadeIn(fast) it'll be .fadeIn("fast"). Same for .fadeOut().
And in general since you're already using jQuery it's better to wrap your code like this:
$(function () {
// Code goes here
});
It looks like you're using jquery selectors (a javascript library). If you're going to use jquery make sure the library is loaded properly by including it in the document header (google makes this easy by hosting it for you <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>)
With jQuery loaded you can do it like this
$(document).ready(function(){
if ($('.div1').is(":visible")) {
$('div2').hide();
}
else if ($('.div2').is(":visible")) {
$('div1').hide();
}
});
WORKING EXAMPLE: http://jsfiddle.net/HVDHC/ - just change display:none from div 2 to div 1 and click 'run' to see it alternate.
You can use setTimeout or setInterval to track if these divs exists
$(function() {
var interval = window.setInterval(function() {
if($('#div2').hasClass('showing')) {
$('#div1').fadeOut('fast');
}
if($('#div2').hasClass('hidden')) {
$('#div1').fadeIn('fast');
}
}, 100);
// when some time u don't want to track it
// window.clearInterval(interval)
})
for better performance
var div1 = $('#div1')
, div2 = $('#div2')
var interval ....
// same as pre code

4 toggle buttons speak javascript to each other but none of them are good listeners

update at the bottom
There are 4 divs that are set to look like toggle buttons. When a button is toggled on:
-it is animated as a pressed button,
-it retrieves some content and it places that content into a box, and then
-it returns a value of 1 to an array.
(no problem.)
Problem:
When there is already one button button pressed, I don't understand how to toggle the first button off without also turning the other one off or affecting the other buttons. How can I pass the output of one button to the others so they know who they have to turn off when they turn on?
My solution thus far has been to create 2 arrays:
var arrayValues [ a, b, c, d]; //the values of each button state: [0,0,0,0] <-all off | all on-> [1,1,1,1]
var addedValues = [a + b + c + d]; //the values of each array item added together: [0+0+0+0]= 0 <-all off | all on-> [1,1,1,1]=4
and then
if (addedValues = 0) {
console.log("cool, nothing is pressed yet. I am going to return true, but where does that return value go? How can I access it?");
return true;
} else if (addedValues > 1) {
console.log("ok I now know that at least one button has already been pressed, but how can I tell the other buttons which one was already pressed?");
}
For example if the first button is toggled on
arrayValues = [1,0,0,0]
and now the second button has been toggled on so it says
arrayValues = [1,1,0,0]
but how can I pass that information into all of the buttons? This next part is obviously flawed but it's the only thing I could think of doing:
} else if(addedValues >= 2) {
arrayValues[0] = arrayValues[0] - 1;
arrayValues[1] = arrayValues[1] - 1;
arrayValues[2] = arrayValues[2] - 1;
arrayValues[3] = arrayValues[3] - 1;
}
so now, the only values that are not negative are the two buttons in active states... but that does nothing for because we already knew that. How can I tell the buttons which button to subtract 1 from without affecting any of the other buttons?
Update: To see the madness in context http://jsfiddle.net/Luhring/EjW7A/23/
*update: *
Just to clarify: the buttons aren't only just toggling their appearances, they're changing other content displayed on the page:
When you click each button the content changes. each button has 1 original group of original content that is toggled on/off with the button. like changing the channel on a tv screen with a remote control.
so if button 1 is pressed, when button 2 is pressed button 1 must turn off (removing its' content and animating back up to its' original position) in order to allow button 2's stuff to display.
shout out to #nbrooks for writing 4 lines of code that more or less did as much as I did in +100. Still not solved but his is WAY more efficient than mine (you can see his version here: http://jsfiddle.net/EjW7A/20/ ) )
Updated Demo, according to new reqs: http://jsfiddle.net/EjW7A/24/
$(function() {
$('.plain').click(function() {
var newClassName = $(this).is('.selected') ? '' : this.id;
if ($(this).is('#content')) return;
$(this).toggleClass('selected', 1000);
$('#content').attr('class', 'plain '+newClassName);
$('.selected').not(this).removeClass('selected');
});
});​
Update to your fiddle demo
The best way to do this is just give the elements a common class, to which you can bind a click handler and a css rule. This will accomplish your function of only having one button being pressed at a time, plus the ability to turn it on/off without affecting the others.
Javascript (jQuery):
$(function() {
$('.plain').click(function() {
$(this).toggleClass('selected');
$('.selected').not(this).removeClass('selected');
});
});​
HTML
<div id="a" class="plain">
<p>A</p>
</div>
CSS
.plain {
width: 200px; height: 200px; margin: 20px; text-align:center; float: left;
font-size: 100px; color:#fff; background-color:red;
}
p { margin-top: 25%; margin-bottom:25%; }
.selected { background-color: blue; }
If you are doing the submitting with JavaScript, then this should be a much simpler approach: http://jsfiddle.net/EjW7A/15/
HTML
<div id="a" class="a1 toggleButton">
<p>A</p>
</div>
<div id="b" class="b1 toggleButton">
<p>B</p>
</div>
<button id ="test">test</button>​
JavaScript
jQuery(function() {
jQuery(".toggleButton").click(function() {
jQuery(".toggleButtonToggled").removeClass("toggleButtonToggled");
jQuery(this).addClass("toggleButtonToggled");
});
jQuery("#test").click(function() {
var value = jQuery(".toggleButtonToggled:first").attr('id');
alert("Toggled button is: "+ value);
});
});​

Unable to get correct offset of floated div

<div id="content">
<div class="oddpost">
<div class="arrow"></div>
</div>
<div class="oddpost">
<div class="arrow"></div>
</div>
<div class="oddpost">
<div class="arrow"></div>
</div>
<div class="oddpost">
<div class="arrow"></div>
</div>
</div>
$(function() {
if (($(".oddpost").position().left + $(".oddpost").width()) >= $("#content").width()) {
$('.arrow').hide();
}
});
http://jsfiddle.net/Ek5Gy/52/
In the code, I have a div(.arrow) nested on another div(.oddpost). What I want to do is hide the .arrow of the left .oddpost only. The idea is .arrow hides when .oddpost is near the left side of #content.
I've tried using offset but it gives the same offset().left value on all the oddpost div so all the arrow div still hides, even the one on the right.
Can anybody tell me how to fix this?
Your main problem lies in your selector usage:
// selecting stuff
$(".oddpost")
// doing stuff on the selection
.position().left
But, you'll have to know how those helper methods work on the given set. position (and many others) will only work on the very first element in the set. Not on every element.
So what you have to do is, iterate over each element in the set and do the test for every element independently, like:
$(".oddpost").each(function () {
if ($(this).prev().length === 0 || $(this).offset().left < $(this).prev().offset().left) {
$('.arrow', this).hide();
}
});
// or
$(".oddpost").each(function () {
if ($(this).position().left === 0) {
$('.arrow', this).hide();
}
});
http://jsfiddle.net/Ek5Gy/53/
The position() call returns values for the first selected element (it doesn't work on all selected elements as many other jQuery calls). Check Javadoc.
This is working for me:
$(function(){
$(".oddpost").each (function (idx, el) {
if ($(el).position().left < $(el).width()) {
$('.arrow', el).hide();
}
});
});
The modified jsfiddle: http://jsfiddle.net/Ek5Gy/54/
In your code, $('.arrow').hide() will always act on all DOM elements that match that particular selector (.arrow). Also, your calculations are only performed once, for the first .oddpost element, since that's the behavior of the position() jQuery function.
I just did not follow exactly what you meant by "near the left of content". I've altered your code a bit to reflect all these changes and prepared a little jsFiddle. Check it here.
Your example works fine.
In your example the value of:
$(".oddpost").position().left + $(".oddpost").width() // Equals 100
This is less the total of #content which is 270px. Your asking if it's greater than or equal too. If you want to hide the arrow when it's near the left try this:
if ($(".oddpost").position().left === 0) {
$('.arrow').hide();
}
EDIT:
$(function(){
$(".oddpost").each(function(){
var position = $(this).position().left;
alert (position);
if(position === 0){
// Do what you need to here.
}
});
});
This is what your looking for...

Categories

Resources