Script not working on first click only on second - javascript

I'm new to js and I have this problem
I want on click to change a height of one element to width of another element
and this code works properly by for some reason I have to click twice, any suggestions how to make it to work on first click?
<script>
var l = document.getElementById("tablinks");
l.onclick = function(){
var w = document.getElementById("img1").offsetWidth;
document.getElementById("beforeafter1").style.height = w + "px";
};
</script>

Try below script.
<script>
//var l = document.getElementById("tablinks");
function doMyTrick(){
var w = document.getElementById("img1").offsetWidth;
document.getElementById("beforeafter1").style.height = w + "px";
};
</script>
<input type="button" onclick="javascript:doMyTrick()" value="Submit"/>

The link/button code is missing, but I guess you didn't put return false; to your javascript code:
<a href='#' id="tablinks" onclick='someFunc(3.1415926); return false;'>Click here !</a>

Related

Javascript - 2nd button click clears my div

im fairly new to JS and ive created a formula to do some calculations and put them into a div when its done. My problem is on the first button press it works like a charm. When i press the button a second time it deletes the text in my div and doesnt redo the calculation.
Its probably some silly mistake i cant find but id appreciate any help. The Code looks like this:
function formChanged() {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
}
document.getElementById('button').click = function calc() {
var x = parseFloat(document.getElementById("x").value);
var y = parseFloat(document.getElementById("y").value);
document.getElementById("test").innerHTML = "pre-text";
while (y < x) {
document.getElementById("test").innerHTML += "text" + x + "more text";;
y++;
}
document.getElementById("test").innerHTML = "post-text";
}
<form>
<input value="20" id="x" type="text" onkeyup="formChanged()" onchange="formChanged()">
<input value="1" id="y" type="text" onkeyup="formChanged()" onchange="formChanged()">
<button type="button" id="button">Calc</button>
</form>
<div id="test" style="height:400px; width:500px; overflow-y: scroll;"></div>
I tried to slim it down a bit since its a bigger loop with calculation etc. The function itself works fine though.
document.getElementById("test").innerHTML = "post-text";
this part removes your div content, just change it with :
document.getElementById("test").innerHTML += "post-text";
Calc
Full working code:
<div id="test" style="height:400px; width:500px; overflow-y: scroll;"></div>
<script>
function calc() {
var x = parseFloat(document.getElementById("x").value);
var y = parseFloat(document.getElementById("y").value);
document.getElementById("test").innerHTML = "pre-text";
while (y < x) {
document.getElementById("test").innerHTML += "text" + x + "more text";;
y++;
}
document.getElementById("test").innerHTML += "post-text";
}
</script>
And ofcourse you can use element.addEventListener("click", calc)like SimpleJ mentioned.
document.getElementById('button').addEventListener("click", calc);
I copied your code into a file and tried it. Your button doesn't do anything.
Edit: As #SimpleJ stated, calling globally is a bad practice. I updated the answer.
function calc(){
// function body
}
document.getElementById('button').addEventListener("click", calc);
This way the calc() function is actually called when you click the button. It's called adding an EventListener if you need some term to Google for further reference.
I hope this is what you need.

What code is required to swap a javascript variable (trailimage) to another when clicking within a website

When clicking (onmousedown or onclick) for example, I would like to change the variable of the trailimge in the javascript to another image. You see, I have an image (a hand) that is following the cursor coordinates. I am unable to code and change the current image to swap to another trailimage after clicking. I will also need to find a way of reverting to the original trailimage when unclicking. The affect will seem as though the handis tapping or pointing.
var trailimage=["images/contact/gardening-glove-cursor.png", , ]
I believe the answer may be within some form of swap variable scripting
e.g.
var a = 1,
b = 2;
var foo = 1;
var bar = 2;
foo = [bar, bar = foo][0];
Trailimage javascript excerpts
var trailimage=["images/contact/gardening-glove-cursor.png", , ]
var offsetfrommouse=[-110,5]
var displayduration=0
if (document.getElementById || document.all)
document.write('<div id="trailimageid" style="position:absolute;visibility:visible;left:0px;top:100px;width:1px;height:1px"><img border="0" src="'+trailimage[0]+'"></div>')
function followmouse(e){
var xcoord=offsetfrommouse[0]
var ycoord=offsetfrommouse[1]
if (typeof e != "undefined"){
xcoord+=e.pageX
ycoord+=e.pageY
}
</script>
Try this
Fiddle
var trailimage = ["http://img2.wikia.nocookie.net/__cb20130626213446/elderscrolls/images/2/2d/TES3_Morrowind_-_Glove_-_Black_Left_Glove.png",
"http://img2.wikia.nocookie.net/__cb20130626213454/elderscrolls/images/9/91/TES3_Morrowind_-_Glove_-_Black_Right_Glove.png"]
$(function() {
$(".logo").attr("src",trailimage[0]);
$(document).mousemove(function(e) {
$('.logo').offset({
left: e.pageX,
top: e.pageY + 20
});
});
$(document).on("mousedown",function() {
$(".logo").attr("src",trailimage[1]);
})
$(document).on("mouseup",function() {
$(".logo").attr("src",trailimage[0]);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logo" src="//ssl.gstatic.com/images/logos/google_logo_41.png" alt="glove" />
Possible Duplicate How do I change the style of the cursor with JQuery?
you can specify like
$('#trailimageid').css('cursor', 'url(' + trailimage[i] + ')');
assuming i as array index

use setTimeout with addEventListener to recall function with same element

I have a div that expands and retracts to show/hide content. I'm using buttons with addEventListner to show/hide the div. I have more then one div I want to show/hide and more than one set of show/hide buttons. I'm therefore trying to reuse the same two functions that show/hide the content but with different event handlers.
The problem I'm having is passing the relevant div id to the function so the function knows whichdiv element to show/hide for each function call. The function recognizes the div id on the first interation however when recalled by setTimeout the div id is no longer recognized. I have tried adding the variable used for div id to setTimeout without any joy.
I'm aware I can use inline javascript for this but am trying to avoid that.
Any ideas how I can solve this using external javascript as I'm trying here ?
HTML:
<button id='expand'>expand</button><button id='retract'>retract</button>
<div id="latinText">
<p>...some content here</p>
</div>
<button id='expandToo'>expandToo</button><button id='retractToo'>retractToo</button>
<div id='latinText2'>
<p>...some more content here</p>
</div>
Javascript:
function divExp(elem) {
var element = document.getElementById(elem);
var h = element.offsetHeight;
var scrollHeight = element.scrollHeight;
var divTimer = setTimeout(divExp, 20);
if(h < scrollHeight) {
h += 5;
} else {
clearTimeout(divTimer);
}
element.style.height = h+'px' ;
}
function divRetract(elem2) {
var element = document.getElementById(elem2);
var h = element.offsetHeight;
var retTimer = setTimeout(divRetract, 20);
if(h > 0) {
h -= 5;
} else {
clearTimeout(retTimer);
}
element.style.height = h+'px' ;
}
document.getElementById('expand').addEventListener('click', function(){ divExp('latinText'); }, false);
document.getElementById('retract').addEventListener('click',function (){ divRetract('latinText') }, false);
document.getElementById('expandToo').addEventListener('click', function(){ divExp('latinText2'); }, false);
document.getElementById('retractToo').addEventListener('click',function(){ divRetract('latinText2'); }, false);
I am not sure if I understood exactly what the problem is, but it sounds like you need to pass an argument to the function you want to call with setTimeout?
var retTimer = setTimeout(function() {
divRetract(elem2)
}, 20);
You should write
var divTimer = setTimeout(function(){divExp(elem)}, 20);
instead of
var divTimer = setTimeout(divExp, 20);
than You'll pass the same element to a function, called by timeout. Otherwise You call divExp() function without parameters

How to make a function set css width with a JavaScript variable?

I have this code:
...<script>
function handleSize()
{
var setObjectSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setObjectSize + "px";
document.getElementById("spin").style.height=setObjectSize + "px";
}
</script>
</head>
<body>
<section id="spin" onLoad="handleSize()">...
All I am trying to do is to create a function that will set the height and width of the element according to window size using a formula and make sure height and width are the same. I am very new to javascript (almost know nothing about it), so despite there being a ton of example of such questions, and me following them, I can't get this code to work. What am I doing wrong?
The problem that I'm seeing, is that the onload event for the section tag isn't firing. You should add your javascript as a self-executing anonymous function to the end of your body tag and this will work for you.
<body>
<section id="spin" style="border:5px solid black;"></section>
<script>
(function () {
var setWindowSize = window.innerWidth - 600;
document.getElementById("spin").style.width = setWindowSize + "px";
document.getElementById("spin").style.height = setWindowSize + "px";
})();
</script>
</body>
See Here for a demo: http://jsfiddle.net/T7DW6/
You should move onload to the body tag:
<body onLoad="handleSize()">
<section id="spin">...
I would suggest you to use jQuery, that is JavaScript library used world wide. So in order to develop it using jQuery you need to do next
function setElementSize(elId) {
var _w $(window); //to get instance of window
var _el $('#' + elId); //jquery to get instance of element
var _width = _w.width();
var _height = _w.height();
//set width=height
if(_height>_width)
{
_height = _width;
} else { _width = _height; }
_el.css({
width: _width,
height: _height
});
}
//this will execute script when document is loaded.
$(document).ready(function(){
setElementSize('spin');
});
Function above will set width and height of element to match window size. If height > width then it will use width as width & height otherwise it will use height.
I assume that you want to change this automatically if window is resized then do this
$(window).resize(function(){
setElementSize('spin');
});
The onload event occurs when an object has been loaded.
onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
onload is only Supported by the Following HTML Tags:
body, frame, frameset, iframe, img, input type="image", link, script, style
from here: event_onload
then a is may be not the best here (height and weight does not change anything, you should use a div.
In order to know, the one to use, please read this:
what-is-the-difference-between-section-and-div
I try your exam and it works fine. The only thing that i changed was the way that you call the function
function handleSize(){
var setWindowSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setWindowSize + "px";
document.getElementById("spin").style.height=setWindowSize + "px";
}
window.onload = function () {
handleSize();
}
I think that onLoad="handleSize()" have to be onload="handleSize()" but don't use that way because it is not a good practise!
this works for me
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button and watch it grow.</p>
<button id = "myButton" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var w = window.innerWidth;
var h = window.innerHeight;
var x = document.getElementById("myButton");
x.style.width = w + "px";
x.style.height = h + "px";
}
</script>
</body>
</html>

Getting Browser size using HTML page

I have a button and When its clicked it calls an alert that gets the browser size but it just says undefined x undefined. If I remove the function part then it will work correctly. How do i get it to work with the button click?
<input type="button" onclick="alertME()" value="Finish">
<script>
function alertME()
{
alert (screen.width + 'x' + screen.height);
}
</script>
When you are getting the undefined message, did you open the file with firefox? If so which version? I know mine works fine with this code (v17) In older versions screen probably isn't supported.
When you are getting the undeafsfined message,asf did you open the file with firefox? If so which versafdsgion? I know minedadg works fine with this code (v17) In older versiodagadgns screen probably isn't supported.dfkjngdojsndosgdg
Try the following:
<input type="button" onclick="alertME()" value="Finish">
<script>
function alertME()
{
var width = document.body.offsetWidth;
var height = document.body.offsetHeight;
alert (width + 'x' + height);
}
</script>
This fixed it for me on jsFiddle:
var width = screen.width;
var height = screen.height;
window.alertME = function()
{
alert(width + 'x' + height);
}
HTML:
<input type="button" onclick="alertME();" value="Finish">

Categories