How can I make an input change its src with an onclick? - javascript

I'm trying this and my background changes color (what I want) but the src of the input only changes on the second time I click it. how can I make it change the source on the first click? Also how can I change the src back to the original with a second click?
<input id="showHideContainer" type="image" src="on.png " height="3%" width="2%" alt="On" onclick="toggle();">
<script>
document.getElementById('showHideContainer').onclick = function () {
divTest = document.getElementById('header');
if (divTest.style.display === "none") {
divTest.style.display = 'block';
} else {
divTest.style.display = "none";
};
$('body').toggleClass('style2');
$('#showHideContainer').click(function(){
$('#showHideContainer').attr('src', 'off.png');
});
}
</script>

You need to determine the current state of the obj then toggle it with the other
$('#showHideContainer').click(function(){
var off = $(this).attr('src').indexOf('off.png')>-1;
$(this).attr('src', (off?'on.png':'off.png'));
});

Quick fix. You are now attaching anoter eventhandler on the first click on the #showHideContainer, that is why it's not firing the first time. This trimmed version of your code should get you the expected result, also see the other answer to look at the state of your element attribute:
document.getElementById('showHideContainer').onclick = function () {
divTest = document.getElementById('header');
if (divTest.style.display === "none") {
divTest.style.display = 'block';
} else {
divTest.style.display = "none";
};
$('body').toggleClass('style2');
var off = $(this).attr('src').indexOf('off.png')>-1;
$(this).attr('src', (off?'on.png':'off.png'));
}

Related

Setting onclick on parent results on parent executing onclick without intention Javascript

I have a layout which I dont think its necessary to post here. But its basically a parent div with a very small width and height that stays on bottom right of a page, if clicked on it, it enlarges width and height.
Here where I had issue:
The parent contains onclick, if its click, it then change its size as well as disabling its onclick and adding onclick to an image, which is a button to minimise the parent div to its original size.
If the image is clicked then again, I disable the onclick on the image and add onclick on the main parent. However Javascript is executing onclick on the parent as it thinks its been clicked, since the image is inside the parent.
To fix this issue I had to set a setTimeout to add the onclick to the parent, that solved the issue, but is there a better way, and why does that happen?
Tahnks
function adjust_window_displayed(el, main_el){
var val = el.value;
var img_el = document.getElementById("img_envelope");
if(val === "true"){
document.getElementById("display_mail_info").style.display = "block";
img_el.src = "https://co.uk/minimise.png";
img_el.style.cursor = "pointer";
main_el.style.cursor = "default";
main_el.onclick = function () {
return false;
};
el.value = "false";
img_el.onclick = function () {
adjust_window_displayed(el, main_el);
console.log("first");
};
console.log("first " + main_el.className);
}else{
document.getElementById("display_mail_info").style.display = "none";
img_el.src = "https://dco.uk/envelope.png";
img_el.style.cursor = "default";
main_el.style.cursor = "pointer";
el.value = "true";
img_el.onclick = function () {
return false;
};
setTimeout(function() {
main_el.onclick = function () {
adjust_window_displayed(el, main_el);
console.log("sec");
};
}, 700);
console.log("second " + main_el.className);
}
}
What happens is due to the event bubble, when you click on the <img> the click event fire once, then a second time for the parent, now if you don't handle that in your function properly it'll give you problems.
Now I have no idea how you're calling that function nor what parameters, you're passing to it, so i tried to reproduce the problem myself.
If you would assign the click event useing the .onclick = function(){}
you can use it to alter between the two, since you're using the same function.
document.querySelector('#parent').onclick = lol;
function lol(e){
var type = e.target.nodeName;
if (type == "DIV")
{
if (e.target.onclick)
{
alert('clicked parent');
e.target.onclick = "";
document.querySelector('#kid').onclick = lol;
}
}
else if (type == "IMG")
{
if (e.target.onclick)
{
alert('clicked kid');
e.target.onclick = "";
document.querySelector('#parent').onclick = lol;
}
}
}
#parent{
width: 500px;
height: 500px;
background-color: red;
}
img{
width: 10%;
height: 10%;
}
<div id="parent">
<img id="kid">
</div>

How to close a picture after displaying it?

I wrote JavaScript code that displays an image on click for my site. How do I add a way for it to close after users are done?
function picture() {
var a = document.getElementById('QR');
a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
a.style.display = 'block';
}
<img id="QR" src="https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg" style="display:none;" />
<button onclick="picture()">Apoyar</button>
https://jsfiddle.net/dmtakr3w/
To close that image after displaying it, you can remove the node by taking the parent element and invoking .removeChild(node); on the parent element.
function closePicture() {
var a = document.getElementById('QR');
var parent = a.parentNode;
console.log(parent);
parent.removeChild(a);
}
If you assign this function to a button you are able to close the image by clicking it:
<button onclick="closePicture()">Close</button>
You can also do a setTimeout() to automatically close the image after a certain amount of seconds or so:
// Removes the image after 5 seconds upon opening:
function picture() {
var a = document.getElementById('QR');
a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
a.style.display='block';
setTimeout(function() {
var a = document.getElementById('QR');
a.parentNode.removeChild(a);
}, 5000);
}
As Sag1v said in the comments, just add an on click event to the QR code tag and switch the display back to none.
function picture() {
var a = document.getElementById('QR');
a.innerHTML = "https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg";
a.style.display = 'block';
}
function closePicture() {
var a = document.getElementById('QR');
a.style.display = 'none';
}
<img id="QR" src="https://www.yoapoyord.com/wp-content/uploads/2017/09/Elfactor3.jpg" style="display:none;" onclick="closePicture()" />
<button onclick="picture()">Apoyar</button>

jquery show hide each div onclick

I have a dynamic number of divs which generated through asp.net. I need to show each div contents by clicking on its header. I have tried this {
$(function () {
var myHead = $(".toggle-container").find(".toggle-header");
var myBody = $(myHead).parent().find(".toggle-content");
$(myHead).click(function () {
if ($(myBody).css('display') === 'none') {
$(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
$(this).parent().find(".toggle-content").slideDown("slow");
} else if ($(myBody).css('display') === 'block') {
$(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
$(this).parent().find(".toggle-content").slideUp("slow");
};
});
});
But it's working only for first header and rest of the headers doesn't collapse it's children content. Here is the JsFiddle Link what I have tried so far. Can anyone give a fix?
The problem was how you were finding the content to be displayed/hidden. You need to find the content related to the clicked header you the code var myBody = $(myHead).parent().find(".toggle-content"); should go inside the click handler as var myBody = $(this).next()
$(function () {
var myHead = $(".toggle-container .toggle-header");
$(myHead).click(function () {
var myBody = $(this).next()
if ($(myBody).css('display') === 'none') {
$(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
$(this).parent().find(".toggle-content").slideDown("slow");
} else if ($(myBody).css('display') === 'block') {
$(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
$(this).parent().find(".toggle-content").slideUp("slow");
};
});
});
Demo: Fiddle
Note: Still the up-down arrows are nor working because you need to use find() instead of children()
But it can be simplified as
jQuery(function ($) {
var $heads = $(".toggle-container .toggle-header");
$heads.click(function () {
var $this = $(this);
$this.find('i').toggleClass('icon-chevron-sign-down icon-chevron-sign-up');
$this.next().slideToggle("slow");
});
});
Demo: Fiddle
The below would work.
In your original code you had assigned the variable myBody a value at the time of load itself. Since there are many such elements, it used only the first one.
Now I have moved the value setting for the myBody variable to be inside the click event and used $(this). This will make sure that it always finds the element in relation to the current element that was clicked.
$(function () {
var myHead = $(".toggle-container").find(".toggle-header");
$(myHead).click(function () {
var myBody = $(this).parent().find(".toggle-content");
//console.log('yes');
if ($(myBody).css('display') === 'none') {
$(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
$(this).parent().find(".toggle-content").slideDown("slow");
} else if ($(myBody).css('display') === 'block') {
$(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
$(this).parent().find(".toggle-content").slideUp("slow");
};
});
});
Fiddle Demo

How to Hide an Image, if not clicked, in N seconds?

I have a button that when is clicked, an image is created using javascript and get prepended to a div (adds it inside a div).
var image = new Image();
var imageHtml = image.toHtml();
$('div.board').prepend(imageHtml);
function Image()
{
this.toHtml = function ()
{
return '<img src=\"myImage.png\" width=\"40px\" height=\"40px\" />';
}
}
This image can be clicked in 2 seconds then user will have 1 more score and if not clicked in that time, then the image should disappear.
How to do that in javascript?
Thanks,
function start_game(image){
var timeout = null;
image.onclick = function(){
clearTimeout(timeout);
//addScore();
};
timeout = setTimeout(function(){
image.onclick = null;
image.style.display = "none";
// remove the image from dom if needed;
}, 2000);
}
Demo: http://jsfiddle.net/UpNCb/
see this, just difference is you going to hide instead of link display
or
give id 'img_id' to your image
function hideimage() {
document.getElementById('img_id').style.display = 'none';
}
setTimeout(hideimage, 10000);
Use the function setTimeout() and the CSS property display or visibility.

Page resets after javascript function finishes

I'm doing a simple html page for a project.
I have a submission form.I use jquery to validate it (no sure if i'm doing ir right).
After the submission is validated,i want to save the user's details(name,password),in an array. The array is created when the script loads.
I added the function SubmitUser() to the onclick event,but when the function finishes,and adds the user,the page resets,and the variables are reset.
I wonder if someone could point out to me what i'm doing wrong.
Thanks in advance,
Boris
Here's the script code:
var userArray = new Array();
var passArray = new Array();
var userNumber = 0;
//Adding rules for validation
$(document).ready(function(){
$("#registerForm").validate({
rules: {
password: {
required: true,
minlength: 8
}
}
});
});
//Add a method to validate
$(document).ready(function(){
$.validator.addMethod("username", function(value, element) {
return this.optional(element) || /^[a-zA-Z]+$/i.test(value);
}, "Field must contain only letters");
});
//The function in question
function SubmitUser()
{
if($("#registerForm").valid())
{
var user = document.getElementById('username');
userArray[userNumber] = user;
userNumber++;
alert('Registered');
}
//Function to switch between the different pages in the menu.
function toggle(id) {
if(id=='LoginPage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('WelcomePage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
if(id=='WelcomePage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('LoginPage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
if(id=='RegisterPage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('WelcomePage').style.display = 'none';
document.getElementById('LoginPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
if(id=='GamePage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('WelcomePage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('LoginPage').style.display = 'none';
}
return false;
}
If you're looking to override the form's natural submit behavior, you can do this:
$(document).ready( function(){
$('#registerForm').submit( function(e){
e.preventDefault(); // suppress natural submit behavior
submitUser(); // your function
});
});
And since you're already using jQuery, you can greatly simplify your toggle code. For each block like this:
if(id=='WelcomePage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('LoginPage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
...you can instead do this:
if( id === 'WelcomePage' ){
$('#'+id).show();
$('#LoginPage, #RegisterPage, #GamePage').hide();
}
Or even more generally, handle all your toggling cases with one line:
function toggle(id){
$('#LoginPage, #RegisterPage, #GamePage, #WelcomePage')
.hide()
.filter('#'+id).show();
}
You can try adding this to your onclick event (on your 'submit' button):
onclick="javascript:return SubmitFunction();"
OR in your form tag (For normal submit button):
onSubmit="javascript:return SubmitFunction();"
Make sure you are returning true or false in your function. if false is returned page won't reset/refresh.
When the page refreshes or changes, the JavaScript variables are reset... Thats the unfortunate truth. Make sure the function that the form is on returns false to stop it from changing the page - so SubmitUser() should look like:
function SubmitUser()
{
if($("#registerForm").valid())
{
var user = document.getElementById('username');
userArray[userNumber] = user;
userNumber++;
alert('Registered');
}
return false;
}
Now, to change pages look at using jQuery.html (Link) to load content in without actually changing the page (or jQuery.load (Link) to load an actual file, like games.html):

Categories

Resources