If a checkbox is checked or unchecked - code optimization - jquery [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
So I have a jquery "checkbox checked/unchecked" function working well. This is a checkbox for turning on or off a particular URL parameter - BUT I believe this code could be written a lot tighter. Does anyone have any suggestions?
$('#mapControl').live('click', function(){
var thisUrl = $(location).attr('href');
if($(this).is(':checked')) {
var lastFour = thisUrl.substr(thisUrl.length - 4);
var param;
if (lastFour == 'com/') {param='?mapControl=true'} else {param='&mapControl=true'}
thisUrl=thisUrl+param;
} else {
$('#urlParam').val(thisUrl);
if (thisUrl.indexOf('?mapControl=true') >= 0){
thisUrl=thisUrl.replace('?mapControl=true','');
} else if (thisUrl.indexOf('&mapControl=true') >= 0){
thisUrl=thisUrl.replace('&mapControl=true','');
}
}
$('#urlParam').val(thisUrl);
});

Try to avoid jQuery as much as you can for example
$('#mapControl').live('click', function(){
// you can directly read window location href attribute
var thisUrl = window.location.href;
var urlParamObj = $('#urlParam');
// instead of $(this).is(':checked') YOU can write *this.checked === true*
if(this.checked === true) {
var lastFour = thisUrl.substr(thisUrl.length - 4);
var param;
if (lastFour == 'com/') {param='?mapControl=true'} else {param='&mapControl=true'}
thisUrl=thisUrl+param;
} else {
urlParamObj.val(thisUrl);
/* if you are sure that your location may have "?mapControl=true" OR "&mapControl=true"you don't have to write code to check string directly replace
*/
thisUrl=thisUrl.replace('?mapControl=true','');
thisUrl=thisUrl.replace('&mapControl=true','');
}
// you don't have to write $('#urlParam') 2 times create a object and refer it again and again
urlParamObj.val(thisUrl);
});

Related

how to hide and show sidenavbar in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
javascript
as see in the js code I m trying the method but I'm struggling to do it js code is not working as well smoothly what I want to write this code and run I m so stuck lots of time to try
var menu = document.getElementById('menu');
var sidenav = document.getElementById('sidenav');
sidenav.style.right = "-300px";
menu.onclick = function () {
if (sidenav.style.right = "-300px")
sidenav.style.right = "0px"
}
else {
sidenav.style.right = "-300px"
}`enter code here`
You need to use == instead of =, and the else need to be inside the function
var menu = document.getElementById('menu');
var sidenav = document.getElementById('sidenav');
sidenav.style.right = "-300px";
menu.onclick = function () {
if (sidenav.style.right == "-300px")
sidenav.style.right = "0px"
else
sidenav.style.right = "-300px"
}
When you use = you change the variable at the left term to the value of the right term, when you use == you check if the terms at each side are equals.
First off, whatever element you want to move needs to have a css position attribute. For example
#sidenav {
position: relative
}
Also here is a rewrite of your code
var menu = document.getElementById('menu');
var sidenav = document.getElementById('sidenav');
sidenav.style.right = "-300px";
menu.onclick = function () {
if (sidenav.style.right == "-300px") {
sidenav.style.right = "0px"
}
else {
sidenav.style.right = "-300px"
}
Note the curly brace that was in front of your if statement

If statements JavaScript, maths will not work in my else statement what am I doing wrong? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This question is pretty straightforward. I am making a number guessing game and I am now adding an attempts function to my game. Every failed attempt should add 1 to my attempts variable:
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
console.log("Attempts:",attempts)
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
console.log("Attempts:",attempts)
}
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
However the else statement argument doesn't work. Each attempt does not add anything to my attempts variable. Can anyone see what is wrong? Thanks in advance.
Note: the else statement is not working for anything mathematical.
You are defining a variable everytime you click.
Removing the "var" from inside the if/else block
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
<script type="text/javascript">
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
}
</script>
Your problem is that when you use the var keyword, you are making a new variable. You should remove the var inside both the if and the else. This will let you change the outer attempts variable, and not the new one that you define by using the var.
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
console.log("Attempts is: "+attempts);
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
I think that I understand what you are having a problem with. You expect what is already logged to the console to change when the variable changes. That's not how console.log works. It only logs the current value of the variable. If you want to see the new value, you should log it again, in this case after each guess is made.

Javascript doesn't work in Internet Explorer but in all other browsers. Why? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The below Javascript (triggering the pagination background color of an element, when another element scrolls into view) doesn't work in Internet Explorer but in all other browsers. Does anyone have any idea why?
The code basis is also available in my pen: https://codepen.io/headstarterz/pen/PMdZdV/
<script>
function inViewport(element) {
// Get the elements position relative to the viewport
var bb = element.getBoundingClientRect();
// Check if the element is outside the viewport
// Then invert the returned value because you want to know the opposite
return !(bb.top > innerHeight || bb.bottom < 0);
}
var project1 = document.querySelector(".project-trigger1");
var project2 = document.querySelector(".project-trigger2");
var project3 = document.querySelector(".project-trigger3");
var pagination1 = document.querySelector(".bullet1");
var pagination2 = document.querySelector(".bullet2");
var pagination3 = document.querySelector(".bullet3");
// Listen for the scroll event
document.addEventListener("scroll", event => {
// Check the viewport status
if (inViewport(project1)) {
pagination1.style.background = "#e3e3e3";
} else {
pagination1.style.background = "transparent";
}
});
document.addEventListener("scroll", event => {
// Check the viewport status
if (inViewport(project2)) {
pagination2.style.background = "#e3e3e3";
} else {
pagination2.style.background = "transparent";
}
});
document.addEventListener("scroll", event => {
// Check the viewport status
if (inViewport(project3)) {
pagination3.style.background = "#e3e3e3";
} else {
pagination3.style.background = "transparent";
}
});
</script>
Script works in Chrome, Safari, Firefox, Edge
Script doesn't work in Internet Explorer 11
It is probably two reasons:
Firstly your closing <script> tag is spelled wrong (<skript>).
Also, you're using 'fat arrow functions', which is a feature of ES6. I would look into something like Babel to transpile your code to a I.E. friendly syntax

How to change image on click [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So I want to change an image onClick and change it back oClick.
This is my current code, but for some reason it doesn't work. I can't find out what's wrong with it.
var newsrc = "suspects.png";
var newsrc = "questionmark.png";
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
}; else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
};
};
I´m pretty sure it´s good like this... Why doesn´t it work?
Toggle a image only checking the source
function toggle(){
var img=document.getElementById('img');
img.src=img.src=='url1'?'url2':'url1';// needs to be the full url.
}
Regarding you code:
you define newsrc 2 times and so the first one is lost.newsrc is always "questionmark.png"
}; else{
should be
}else{
and
if you have suspects set then you want questionmark if clicked, and not suspects.so invert the if content.
should be
if suspects then questionmark else suspects
you have
if suspects then suspect else questionmark.
DEMO
http://jsfiddle.net/SLkHu/
Remove extra semicolons ; in your code
It should be
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
} else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
}
}

Going to a link with right click [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have several table cells of the type:
<td oncontextmenu=";return false;">
H<br>
2.20
</td>
My question is: How to make a javascript that captures the title of the link, and goes to http://en.wikipedia.org/wiki/TITLE_OF_THE_LINK when I right-click in the coresponding cell?
You can use window.location to redirect the user.
HTML
<td oncontextmenu="gotoWiki(event);return false;">
H<br>
2.20
</td>
JS
function gotoWiki(event) {
// Extract the target from the event
var target = event.target || event.srcElement;
// Get the link
var link;
if (target.tagName == "A") {
// If the target is an <a>-Tag, it's the link
link = target;
} else {
// Otherwise, get the first <a>-Tag
link = target.getElementsByTagName("a")[0];
}
// If getElementsByTagName() returned an element and it has the title attribute
if (link && title = link.getAttribute("title")) {
// Redirect
window.location.href = "http://en.wikipedia.org/wiki/" + encodeURIComponent(title);
}
}
What you're looking for is basically this:
HTML:
<td oncontextmenu="goTitle(this); return false">
h
</td>
JavaScript:
function goTitle(el) {
var link = el.firstChild;
var url = "http://en.wikipedia.org/wiki/" + link.title;
window.location.href = url;
}
For simplicity, it's assumed your link is always the first element in your td

Categories