change image source with javascript - what's wrong? - javascript

<IMG onmouseover="document.swap2.src='http://www.grlf.com/pics/png';" id="brewmp" alt=Brew src=changeOSImage() width=26 height=24>
function changeOSImage() {
var mp_os = "x";
if (mp_os) == "Brew MP") {
document.getElementById("brewmp").src = "http://www.greengo-cellular.com/ebay_files/images/features_n_02.png";
} else {
document.getElementById("brewmp").src = "http://www.greengo-cellular.com/ebay_files/images/features_02.png";
}
};
For some reason instead of changing the url, the url displays the function name inside of it (therefore leading to nowhere). What have I done wrong?

You can not specify a function at the src attribute of an image.
Try putting the changeOSImage() function at the onload event of the document, or calling it from some other function.

As already mentioned, the src of your image cannot be a function. Also I cannot see what document.swap2 actually refers to in your code. try something like
<img id="brewmp" src="http://www.grlf.com/pics/png" />
<script>
window.onload = (function(){
var mp_os = 'x';
document.getElementById('brewmp').onmouseover = (function(){
this.src = 'path/to/different/image';
});
});
</script>
I'm not sure what mp_os is referring to in your initial code as it's set as x and you never change it, plus it is defined within the scope of your function which means it will always be 'x' in this case.The above should give you a good starting point to add your "if" statement into though, but you should declare var mp_os outside of the function

As noted in the other answers, you have an extra ) in your if statement. Try this:
Example: JsFiddle
JavaScript (added inside <head></head>):
<script>
var mp_os = '';
function changeImage(){
if (mp_os == "Brew MP") {
mp_os = "x";
document.getElementById("brewmp").src = "http://png-5.findicons.com/files/icons/75/i_like_buttons_3a/512/perspective_button_stop.png";
} else {
mp_os = "Brew MP";
document.getElementById("brewmp").src = "http://icons.iconarchive.com/icons/mazenl77/I-like-buttons-3a/512/Perspective-Button-Go-icon.png";
}
}
</script>
HTML:
<img onmouseover="changeImage()" onmouseout="changeImage()" id="brewmp" alt="Brew" src="http://png-5.findicons.com/files/icons/75/i_like_buttons_3a/512/perspective_button_stop.png" width="20%">

Related

modify url by clicking a div

I have a page in php, and I'm trying to add an ?id=variable_value extension to it's url when I click on a div, but when I click it gives me an undefined url error with the extension
Here is the script:
<script language="javascript" type="text/javascript">
var Pokemon_ID = 1;
function changeUrl() {
location.href=this.href+'?id='+Pokemon_ID;return false;
}
document.getElementById( 'right-btn' ).onclick = function() {
changeUrl();
};
</script>
And the div :
<div id="right-btn" href="pokedex.php" onclick="changeUrl()">
Don't use two separate ways of attaching handlers when you only need one. Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead.
The problem is that when assigning the handler via onclick, the this in changeUrl is undefined, because the calling context is global. Feel free to avoid using this when it can cause confusion.
Just use addEventListener alone. Also, you'll have to use getAttribute('href') instead of .href because divs are not supposed to have href properties.
const Pokemon_ID = '5';
document.getElementById('right-btn').addEventListener('click', function(e) {
// location.href = e.target.getAttribute('href') + '?id=' + Pokemon_ID;
console.log('changing URL to ' + e.target.getAttribute('href') + '?id=' + Pokemon_ID);
});
<div id="right-btn" href="pokedex.php">text</div>
Try this instead:
location.href += '?id=' + Pokemon_ID;
Because you call changeUrl() within the onclick method you loose the context of this. This in changeUrl is not your div. Maybe you have to pass this into the method with changeUrl(this) or you just pass the href with changeUrl(this.href).
Than use:
function changeUrl(target){
location.href=target.href+'?id='+Pokemon_ID;
}
As mentioned by CertainPerformance above, you are not passing the right arguments to you function to work correctly; Using you code as a reference, you can either pass the original event to you changeUrl() function, then use the e.target to get to your 'right-btn' element.
Javascript:
var Pokemon_ID = 1;
function changeUrl(e) {
var href = e.target.getAttribute('href');
console.log(href +'?id=' + Pokemon_ID);
return false;
}
document.getElementById( 'right-btn' ).onclick = function(e) {
changeUrl(e);
};
HTML:
<div id="right-btn" href="pokedex.php">Click Me 4</div>
However, if you realy want to use this in your function to refer to the 'right-btn' element, then you can change the code to;
Javascript:
var Pokemon_ID = 1;
function changeUrl() {
var href = this.getAttribute('href');
console.log(href +'?id=' + Pokemon_ID);
return false;
}
document.getElementById( 'right-btn' ).onclick = function(e) {
changeUrl.call(e.target);
};
The changes being the call in the event handler:
changeUrl.call(e.target);, which calls you function in the 'context' of the e.target, making the this in your changeUrl() function to the element. Then you can use the this as in var href = this.getAttribute('href');

JS onClick not working

Just don't know why this piece of code is not working: (onClick not working, click() is working (using console))
function click(ID)
{
if(cost[ID] <= currency[costID[ID]])
{
currency[costID[ID]] -= cost[ID];
currency[ID] += buyamout[ID];
document.getElementById(x[costID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[costID[ID]])*100)/100)+not+"</center>";
document.getElementById(x[gainID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[gainID[ID]])*100)/100)+not+"</center>";
}
}
...'<button onClick="click('+i+');">'+button+x[i]+'</button>'
this gives output <button onClick="click(0);">Make DNA</button>
and after clicking button nothing happens.
There could be a namespace conflict with your click. Use another name like button_click below
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="button_click('+i+');" >'+(button+x[i])+'</button>');
function button_click(ID) { // notice the function name change
alert(ID);
}
Code below not working:
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="click('+i+');" >'+(button+x[i])+'</button>');
function click(ID) { // the function name click may have been used already
alert(ID);
}
indeed onclick="click('+i+');" executes the javaScript code between the double brackets: click('+i+');: it calls the javaScript click() function, but this does not work if you declare function click() and someone else did that elsewhere in javaScript code.
if onClick is not working you can also use addEventListener will do the same job.
for e.g.
element.addEventListener('click', function() { /* do stuff here*/ }, false);
To answer your question you must do the following.
Change:
onClick="click(0)"
To:
onclick="click(0)"
That will most probably fix your problem.

Setting and checking localstorage for a certain value, then performing a function based on the data

I'm trying to set local storage from one page("index.html/settest.html"), and check for it on "index.html". If the check comes back with a certain result, it'll execute a function.
I have written some code for this, but it doesn't work. I don't really know why, so I'm hoping to get some assistance here.
Here's what I have on my "settest.html" page. It's really simple -
<script>
window.onload=setlocalstorage() {
localStorage.setItem("one", true);
}
</script>
So the way I understand it, when the page loads, it should set the value of "one" to true in localStorage.
Here's what I have on my "index.html" page -
<script>
window.onload=setInterval(function() {
var one = localStorage.getItem('one') || '';
if (one != 'yes') {
function hideone() {
var elem = document.getElementById("one");
elem.className = "hide";
}
}
}, 1000);
</script>
From what I understand, this should check localStorage every second for "one", and execute the function "hideone" if it comes back yes(or true).
However, when I go to "settest.html", and then visit "index.html", nothing happens. There are no errors in the console, or anything abnormal showing. I just don't get why it won't work.
Thanks in advance, if anyone needs more information or context feel free to ask!
-Mitchyl
You're not defining the window.onload functions correctly. Either:
<script>
window.onload = function() {
localStorage.setItem("one", true);
}
</script>
Or:
<script>
window.onload = loadFunction;
function loadFunction() {
localStorage.setItem("one",true);
}
</script>
And on your other page:
window.onload = function() {
setInterval(function() {
var one = localStorage.getItem('one') || '';
if (one != 'yes') {
function hideone() {
var elem = document.getElementById("one");
elem.className = "hide";
}
}
}, 1000);
};
Additionally, you're setting localStorage.one to true on the first page, and checking if it's yes on the other page. Not sure if this is meant to be or is a mistake.
None of your functions are correctly defined. It looks like you want to do this:
settest.html:
<script>
window.onload=function()
{
localStorage.setItem("one", true);
}
</script>
index.html:
<script>
window.onload = function ()
{
setInterval(function()
{
var one = localStorage.getItem('one') || '';
if (one !== true)
{
var elem = document.getElementById("one");
elem.className = "hide";
}
}, 1000);
}
</script>
Assuming you want it to check every second to see if it needs to set the class on a specific element to 'hide'.

JavaScript generated HTML with onClick doesn't trigger function

The script below adds items to an array when you click the link, and generates a list of items as html output. You can see an example here: http://jsfiddle.net/dqFpr/
I am trying to create a function to delete items from the list. Not a difficult task with splice(), but somehow clicking the delete link doesn't trigger the test_function() function.
Can someone tell me what I am doing wrong, or show me another way of triggering the function? Your help is really appreciated ;-)
<script language="javascript">
$(document).ready(function() {
function test_function( number ) {
/* This function is not triggered, nothing works inside here!! */
}
});
var lines = [];
function update_list( lines ) {
var thecode = '';
for(var i = 0; i < lines.length; i++) {
thecode = thecode + lines[i] + ' <a onclick="javascript:test_function('+i+')" href="#">(delete)</a><br />';
}
$('div#display').html(thecode);
}
$('a#new').click(function() {
lines.push('another line');
update_list(lines);
});
</script>
<div id="display"></div>
Add a new line
Because in the text assigned to display's innerHTML, *test_function* is just plain text that is evaluated by the HTML parser. At that point, its scope is global, not within the IIFE passed to $(document).ready(). You can fix that by making the function global:
$(document).ready(function(){
window.test_function = function (number) {
// do stuff
}
....
});
or
var test_function;
$(document).ready(function(){
test_function = function (number) {
// do stuff
}
....
});
Or whatever method you like to get access to the function. But while it is declared inside an anonymous function's scope, you can only get access to it from a function that has a closure to the variables in that scope.

Color-cycling an element not working?

I am a beginner in javascript, can you tell me what's wrong with the below code?
I want this to invoke buttonPressed() when a button gets pressed. From buttonPressed() it should call changeColor1(), changeColor1() should change the text color of a paragraph, and start a timer to invoke changeColor2(). Similarly changeColor2() should also change the color and call changeColor1() once the timer expires.
<html>
<head>
<script type="text/javascript">
function changeColor2()
{
alert("2");
var v = document.getElementById("onet");
v.style.color = rgb(0,255,255); // this statement is not working
var t=setTimeout(changeColor1,3000);
}
function changeColor1()
{
alert("1");
var v = document.getElementById("onet");
v.style.color = rgb(255,255,0); // this statement is not working
var t=setTimeout(changeColor2,3000);
}
function buttonPressed()
{
alert("Hello");
changeColor1();
}
</script>
</head>
<body>
<p id="onet"> Hello how are you? </p>
<form>
<input type="button" value="Display alert box!" onClick="buttonPressed()" />
</form>
</body>
</html>
Do not invoke the function, pass the reference only:
var t=setTimeout(changeColor2,3000);
I think you want style.color not .color.
By the way... please tell us what the code is supposed to actually do and what is wrong initially.
You need to quote style property values-
v.style.color = 'rgb(255,255,0)';
1) I don't like the fact that you have two timeouts set. Just call one function and use a flag to toggle between the two options.
2) The parameter to setTimeout that you want to use is a function pointer (changeColor) not the result of a function call (changeColor())
var flag = false;
var t;
function changeColor()
{
var v = document.getElementById("onet");
if(flag){
v.color = rgb(255,255,0);
} else {
v.color = rgb(0,255,255);
}
flag = !flag;
}
function buttonPressed()
{
alert("Hello");
t=setInterval(changeColor,3000);
}
Not really knowing what it is you're trying to do, I can tell you that your button's onClick handler references a method name that isn't in your code. Judging by the names of your methods, I think you meant to put "buttonClicked" in there.
Nevermind, looks like you changed it while I was typing.
Instead of v.color = rgb(0,255,255); use v.style.color = "#0ff".

Categories