I have JavaScript code that must move a div up and down. When I click it I want it to go up, then when I click the second time I want it to go down. My code is this:
function why()
{
if (document.getElementById("newton").style.bottom == 23) {
alert("I entered the IF");
document.getElementById("newton").style.bottom = 0;
}
else {
alert("I entered the ELSE");
document.getElementById("newton").style.bottom = 23;
}
}
The strange thing is that the first time I click the div it goes up and tells me the ELSE part was executed, but after this, clicking it won't produce any effect, it wont go back down. Why is this?
You need to specify a unit, like % or px or whatever.
function why() {
if (document.getElementById("newton").style.bottom == '23px') {
alert("I entered the IF");
document.getElementById("newton").style.bottom = 0;
} else {
alert("I entered the ELSE");
document.getElementById("newton").style.bottom = '23px';
};
}
<button id="newton" onclick="why()">click</button>
But I would toggle a class instead and put this change in CSS.
function why(el) {
el.classList.toggle('up');
}
#newton {
bottom: 0;
}
#newton.up {
bottom: 23px;
}
<button id="newton" onclick="why(this)">click</button>
I found out that if other js functions are wrong, it can affect my whole code,even other functions. The code was right, but since another function was wrong that made my code not work...Thanks for the toogle the class advice, I will implement it ;)
Related
Hey everyone i have tried to make three different navigationbars according to the users role. I only want one of the nav bars to be displayed according to if its a guest, user or admin. For now i just want to show the different navigationbar accoring to x=1 or not (se js code).
Can someone help me? I have tired everything by now. But it just wont work. Iam not that good at programming, so please dont make it to complicated.
Javascript file
x = 1
if (x==0) {
(#alle).show;
} else {
("#all").hide;
}
if (x==0){
("#user").show;
} else {
("#user").hide;
}
if (x==101){
("#admin").show;
} else {
("#admin").hide;
}
Use
document.querySelector('#all').style.display = 'none';
There is no built-in methods .hide() or .show() like jQuery has.
If I understand you correct then this is what you have to do:
x = 0;
//Check role, could also do this in switch statement.
//But for now like this since it might be easyer to understand.
//Probably if you copy paste this it wont work but I think this part is needed.
if (user == guest) {
x = 0;
} else if (user == user) {
x = 1;
} else if (user == admin) {
x = 2;
}
//Guest
if (x==0) {
(#alle).show;
} else {
("#alle").hide;
}
//user
if (x==1){
("#user").show;
} else {
("#user").hide;
}
//Admin
if (x==2){
("#admin").show;
} else {
("#admin").hide;
}
Goal:
I want to be able to add comments onto images and use their X,Y coordinates to save the comment and display for later.
Expected Result:
I want a user to click on a "New Comment" button which enables "Comment Mode" and displays a form. If a user clicks away from the form, I want the form to hide and "Comment Mode" to become disabled until the user clicks "New Comment" again. If "New Comment" is pressed again, repeat the above.
Actual Result:
The snippet of code currently allows a user to click "New Comment". Once clicked the commentMode() function is triggered and listens for a click on the #imageWrapper. If the user clicks away, the form is hidden - but when I press "New Comment" again, the form remains hidden.
function commentMode() {
imageWrapper.toggleClass('new-comment-pointer'); // changes cursor to show its active
imageWrapper.click(function(e) { // on clicking the image
newComment = !newComment; // newComment is true
console.log(newComment);
if(newComment) { // if newComment is true, show the form near the click
getCoordinates(e, $('#imageWrapper'));
form.show().css({'left': formX, 'top': formY});
form.find('textarea').focus();
form.find('#xAxis').val(x); // x is from the getCoordinates
form.find('#yAxis').val(y); // y is from the getCoordinates
} else { // if newComment is false, hide the form and turn stop imageWrapper.click
form.hide();
imageWrapper.removeClass('new-comment-pointer');
newComment = !newComment;
return; //stop listening for click
}
return;
});
}
https://codepen.io/lachiekimber/pen/YzzPEqw
I do not know why everybody make it complicated.
First give the form and the button a id. Then define a default form css class which is hidden.Define another ones which makes it visible some kind of:
<style>
.invisible {
display:none;
}
.visible {
display:block !important;
}
</style>
Now we add a document listener which make things more simple instead fiddeling on whatever event...
document.addEventListener(" click ", function(event) {
//try to get a id even when the event element has not
// directly a id but maybee his parent the form
try {
var id = event.target.id;
if (id === "") {
for (i = 0; i < event.path.length; i++) {
id = event.path[i].id;
if (id !== "") {
if (id === "formid") {
break;
}
}
}
} catch(ex){
console.log(ex);
return;
}
var form=document.getElementById("formid");
switch(id){
case "showcommehtbuttonid":
case "formid":
form.classList.add("visible");
break;
default:
form.classList.remove("visible");
}
}
The toggle state has a disadvantage in your case - complicate to handle. Works best by a simple id and button. There is no doubt about then. Adding and removing handlers also makes no real sense. Either the user clicks on the form or the button and the form becomes visible. Or he clicks something else. In this case no id or the "wrong" id will be chosen. In this case the default switch rule make the form invisible. The thing is untested and might need some minor tweaks. And best - in the event handler you can now also add very simple more actions.
As #Davo mentioned in the comments, I attempted to refactor the code. I started by cleaning up the code into functions and not nesting click events. Whilst refactoring, I used console.log's to help me identify when the commentMode was active - then triggered the showForm() or hideForm() functions. For a working example: https://codepen.io/lachiekimber/pen/bGGNYmK
$(function () {
var imageWrapper = $('#imageWrapper');
var form = $('.new-comment');
var x, y, formX, formY;
var newComment = true;
var commentMode = false;
$('#newComment').click(function() {
imageWrapper.toggleClass('new-comment-pointer');
commentMode = !commentMode;
//console.log('newComment');
});
$('#imageWrapper').click(function(e) {
if(commentMode) {
//console.log('commentMode: true');
showForm(e);
} else {
//console.log('commentMode: false');
hideForm();
}
});
function showForm(e) {
getCoordinates(e, imageWrapper);
form.show().css({'left': formX, 'top': formY});
form.find('textarea').focus();
form.find('#xAxis').val(x); // x is from the getCoordinates
form.find('#yAxis').val(y); // y is from the getCoordinates
}
function hideForm() {
form.hide();
}
function getCoordinates(e, image) {
var offset = image.offset();
x = e.pageX - offset.left;
y = e.pageY - offset.top;
formX = x + 50;
formY = y + 20;
}
});
Working and tested :) ! Ok we could work on the page style quite a bit but :d
Look how simple the whole page looks also. I do not have to fight with jquery for this little task :) I set also the autofocus just by plain html.
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<style>
.invisible {
display: none;
border: 1px solid red;
}
.visible {
display: block !important;
}
</style>
</head>
<body>
<form id="formid" class="invisible">
<h1>Form</h1>
<input type="text" name="size" autofocus>
</form>
<hr>
<input type="button" value="click" id="showcommentbuttonid">
<script>
document.addEventListener("click", function(event) {
try {
var id = event.target.id;
if (id === "") {
for (i = 0; i < event.path.length; i++)
{
id = event.path[i].id;
if (id !== "") {
if (id === "formid") {
break;
}
}
}
}
} catch (ex) {
console.log(ex);
return;
}
var form = document.getElementById("formid");
switch (id) {
case "showcommentbuttonid":
case "formid":
form.classList.add("visible");
break;
default:
form.classList.remove("visible");
}
}
)
</script>
</body>
</html>
I am not really sure what code to post here because I don't know what could cause this and the code for this page is quite long, there is still no live version.
Basically it's a form with a few panels, only 1 is visible, when you click next the user is moved to the next screen. What happens is that when you click next there is an unwanted scroll to the footer, any idea what could cause this? view gif below:
EDIT: This is the button code:
Next
and jQuery:
$('.btn-next').on('click', function(e){
if (!$("[name='amount_tobe_charged']").val()) {
alert('Please fill in amount');
} else if($("[name='amount_tobe_charged']").val() < 1) {
alert('Please enter amount');
} else {
var tab = $(this).closest('.tab-pane');
var nxt = $(tab).next();
var empty = $(tab).find('.required').filter(function(){
if($(this).attr('type') === 'email'){
return this.value.indexOf('#') < 0;
} else {
return $.trim(this.value) === '';
}
});
var error = $(empty[0]).attr('data-error') || 'Please fill in all fields';
if(nxt.attr('id') === 'finish-tab'){
submitForm(tab, nxt);
} else {
if(!empty.length) {
changeTab(tab, nxt);
} else {
alert(error);
}
}
}
You can see it happening in your gif. It's because you're hiding a column that comes before the form, therefore once the column does not exist. It will push you down. You can add a scroll to get around with issue with jQuery (or vanilla but I will only provide jQuery's smooth scroll). Either implement the below and remove the style="display: none;" that's causing it to shift.
$('html, body').animate({
scrollTop: $(".form-elem").offset().top
}, 2000);
You'll want to place this after the column is hidden in your JS code.
Novice in programming, this is my practice the code, I can't figure out how to code my concept and I am not sure if I need to use for or while for the following requirement:
After 3 or 5 times the user fails to input something in the prompt box, then a final alert shows up telling something like "No more Opportunities!" and then turns the div background grey color.
Any help will be welcome to help me improve.
JS
var mObjt = {
userInput: "",
setInput: function(){
document.getElementById("div1").innerHTML = mObjt.userInput;
},
conRequest: function(){
if(mObjt.userInput != ""){
mObjt.setInput();
} else {
alert("There is no input!");
mObjt.popRequest();
}
},
popRequest: function(){
mObjt.userInput = prompt("Enter a word:");
mObjt.conRequest();
}
}
HTML:
<div id="div1" style="width:200px; height:30px; border:1px solid;"></div>
<button type="button" onClick="mObjt.popRequest()">Add Property</button>
You shouldn't use any type of loop for that. Keep a counter variable. Every time the user fails, increase the counter. When the counter gets to 5, do whatever needs to be done.
var failCount = 0;
function handleInput() {
// This is a totally fake example just to show you want to do
if(input) {
// Input valid, yay
} else {
// Input invalid
failCount++;
if(failCount >= 5) {
// Disable your stuff
alert('Oh no, input failed: you have no more remaining attempts');
} else {
alert('Oh no, input failed');
}
}
}
I have a list of urls(div) underneath an input field(div). I need the ability to come down in the list and than by hitting enter this will trigger some function designated to the url. This is the fidle: the script
Over the last days I have tried to much things to explain, but in conclusion none of it worked. Help would be appreciated.
After this line of code :
// set timers to do automatic hash checking and suggestions checking
setInterval(checkHash,500);
setInterval(checkSuggest,500);
Insert this :
$('#searchbox').keyup(
function (e){
var curr = $('#suggest').find('.current');
if (e.keyCode == 40)
{
if(curr.length)
{
$(curr).attr('class', 'display_box');
$(curr).next().attr('class', 'display_box current');
}
else{
$('#suggest li:first-child').attr('class', 'display_box current');
}
}
if(e.keyCode==38)
{
if(curr.length)
{
$(curr).attr('class', 'display_box');
$(curr).prev().attr('class', 'display_box current');
}
else{
$('#suggest li:last-child').attr('class', 'display_box current');
}
}
if(e.keyCode==13)
{
var search_terms = $('.current a').text();
// perform a search with this text...
doSearch(search_terms,true,false);
//update the search textbox
$('#searchbox').val(search_terms);
}
})
And don't forget to delete the previous code at the bottom...