Making an img (used as a button) disabled - javascript

the image is:
<img id="lawnButton" src="images/mowing.png" width="15%" height="45%" alt="mowLawn" border="0" onclick="cutLawn()">
The code in the .js is:
document.getElementById("lawnButton").disabled = true;
Is there anything off the bat that I am doing incorrectly? The image still works as a button after the code is executed.

The image tag doesn't have that attribute. Try removing the event.
var lawn = document.getElementById("lawnButton");
lawn.onclick = function() {
//do code
lawn.onclick = null;
}
//.. code to re-enable the trigger
if (some condition) lawn.onclick = cutLawn;

Since images don't have a disabled attribute, you might want to set some flag to it to be used in cutLawn.
You could use a class. For example, to disabled the button:
button = document.getElementById("lawnButton")
button.className = button.className+ " disabled"
And then in cutLawn:
cutLawn = function(){
button = document.getElementById("lawnButton")
if button.className.match(/disabled/){
return false;
}
// ...
}

Related

window. onload=function() just works without cached DOM

The product image is displayed as inline SVG and receives a new color for specific paths, depending on the dropdown selection.
"use strict";
window.onload=function(){
var dropdownColor = document.getElementById('Color');
// When a new <option> is selected
dropdownColor.addEventListener('change', function() {
var selectPathSvg = document.getElementById('pathNumber');
//get value text
var colorValue= selectElemFerse.options[selectElemFerse.selectedIndex].text;
//Clear all Classes from SVGPath
selectPathSvg .classList = '';
// Add that class to the <p>
selectPathSvg.classList.add(colorValue);
})
}
But this Javascript code works only, if the page was read in the DOM for the first time. If you reload this page with F5, this will not lead to any errors in the console, but not to the desired result.
EDIT: Nothing here worked for me. But I noticed that if I delete the `woocommerce_recently_viewed``cookie, that the systems works fine. But how to fix such a thing?
It's generally bad practice to use onload = ... You should instead try using addEventListner("load", ...)
The reason your script does not run, is because it gets compiled after the page has been fully loaded, so you should also check if the load event has already been fired.
"use strict";
if(document.readyState === "complete") onLoad();
else addEventListener("load", onLoad);
function onLoad(){
console.log("Doing on load stuff here...");
}
Try this instead and see if it works:
window.addEventListener('DOMContentLoaded', (event) => {
var dropdownColor = document.getElementById('Color');
// When a new <option> is selected
dropdownColor.addEventListener('change', function() {
var selectPathSvg = document.getElementById('pathNumber');
//get value text
var colorValue= selectElemFerse.options[selectElemFerse.selectedIndex].text;
//Clear all Classes from SVGPath
selectPathSvg .classList = '';
// Add that class to the <p>
selectPathSvg.classList.add(colorValue);
})
});

Disable "Changes you made may not be saved" pop-up window

I use the following frontend code to export a .csv document.
HTML
<form id="tool-export" method="post" action="export/">{% csrf_token %}
<a id="export-link" class="btn btn-sm btn-primary" href="#">DOWNLOAD</a>
</form>
JS
$('#export-link').click(function(e) {
e.preventDefault();
var link = $(this);
var form = link.closest('form');
var project_id = proj_id.find(":selected").val();
var input = $('<input>').attr('type', 'hidden').attr('name', 'project_id').val(project_id);
form.append($(input));
var project_type = proj_type.val();
input = $('<input>').attr('type', 'hidden').attr('name', 'project_type').val(project_type);
form.append($(input));
form.submit();
});
Export works well and I get the correct document. But also I receive the Changes you made may not be saved message after clicking on the export link. How to disable this message? I don't want to see it.
#Dekel helped me to get it.
The message is the beforeunload event.
And I can disable it with window.onbeforeunload = null;.
JS
$('#export-link').click(function(e) {
window.onbeforeunload = null;
e.preventDefault();
var link = $(this);
var form = link.closest('form');
var project_id = proj_id.find(":selected").val();
var input = $('<input>').attr('type', 'hidden').attr('name', 'project_id').val(project_id);
form.append($(input));
var project_type = proj_type.val();
input = $('<input>').attr('type', 'hidden').attr('name', 'project_type').val(project_type);
form.append($(input));
form.submit();
});
In jQuery simply use :
$(window).off('beforeunload');
I had the same problem.
window.onbeforeunload = function () {
// Your Code here
return null; // return null to avoid pop up
}
I've had the same error with embedding Google-Form in Chrome,
I can verify that none of the found solutions helped me. Here is the screenshot of my pop-up:
The only solution I've managed to implement was hiding the element and then unhiding/creating the new iframe with the current embed. Here's the part of my code:
if (oldvalue !== value) { // checks the id of the form (value) is not the same
// set value of the id
$('#info').text(value);
// check the element exists
let exists = value;
if($("#" + value).length == 0) {
//it doesn't exist
exists = false;
}
// hide all child elements of the div for forms
parent.children().hide();
// create new node if needed
if (!exists)
{
// create new form element and embed the form
$("#google-form").clone().attr("id",value).attr('src', record.url).appendTo(parent);
}
// unhide error element
$("#" + value).show();
}
The full code of my solution is here.

HTML href onclick will not trigger javascript function

I have been asked to update my question so here goes:
I have records in a database, some of which have wave file names attached. I am looping through the database and wanting to write out the word "Play" in a column under a header named Audio File. When "Play" is clicked on, the audio player plays the file and turns the href word to "Pause". When my code loops through these records, it is assigning a separate ID to each href. For me to call the function that starts the audio player, I need to send an audioControl ID (aControl) variable as well as the src source file (thissource) variable for the audio player - hence the & and " in the function call. When I use the onclick event in a button, it triggers the function. However, when I click the href link (which is what I want instead of a button) nothing happens. I am not sure which part of the code is messy, as I found the function code on the internet. Thank-you in advance for any and all help.
No matter what I do, my href onclick will not trigger a javascript function. I have taken the return false out of the function and put it in the href but that doesn't work either. I have put the same onclick code in a button and it triggers great.
HTML:
<a href='#' onclick='passvariables(" & aControl & "," & thissource & ");'>Play</a>
Javascript:
function passvariables(aControl, thissource)
{
var yourAudio= new Audio();
yourAudio.src = thissource;
yourAudio.type = 'audio/wav';
ctrl = document.getElementById(aControl);
ctrl.onclick = function ()
{
// Update the Button
var pause = ctrl.innerHTML === 'Pause';
ctrl.innerHTML = pause ? 'Play' : 'Pause';
// Update the Audio
var method = pause ? 'pause' : 'play';
yourAudio[method]();
// Prevent Default Action
return false;
}
}
Just have onclick call passvariables without the return and have passvariables return false.
You can try:
window.passvariables = function(aControl, thissource) {
// Your code
};
My guess if that your function is defined within another function (executed onload for instance). Hence "passvariables" is not defined in the "window" scope.
I saw you updated your questions that's good :)
First I recommend you to use the javascript library jquery which is easier to manipulate the DOM and you can easily find ressources and help on this site.
Here's what your code should look. I haven't tested it but it's a good overview of what this should be.
Put this in the <head> section of your HTML code
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$(document).ready(function() {
//Assigning onClick function for every HTML tags having the css class "Play"
$('.Play').click(function(){
if($(this).html() == "Play"){
//retrieving information about the audio
var waveFile = $(this).attr("data-waveFile");
var audioId = $(this).attr("data-audioId");
//calling the startAudio function and assign the Audio object to myAudioObject
var myAudioObject = startAudio(waveFile, audioId);
if(myAudioObject){
//Audio started playing
$(this).html("Pause");
}else{
alert("error while starting to play file");
}
}else{
var isPaused = pauseAudio(myAudioObject);
if(isPaused){
//The pauseAudio function returned true so the audio is paused
$(this).html("Play");
}else{
alert("error while pausing");
}
}
});
//Functions to manage audio Player
function startAudio(waveFile, audioId){
audioObject = document.getElementById("audio");
audioObject.src = waveFile;
audioObject.play();
return true;
}
function pauseAudio(){
//do whatever to pause
audioObject = document.getElementById("audio");
audioObject.pause();
return true;
}
});
</script>
in the <body> section of your HTML code where you construct the table using database datas :
<table>
<tr>
<td>Song name</td>
<td>Action</td>
</tr>
<tr>
<td><%=WaveFile%></td>
<td>Play</td>
</tr>
</table>
<audio id="audio"></audio>
Note the <%=WaveFile%> and <%=AudioId%> should be the values you get from the database in your loop
Thank-you everyone for your help! I finally got it working! Here is the code:
yAudio = "'yourAudio" & thisline & "'"
aControl = "'audioControl" & thisline & "'"
thissource = "'/WaveFiles/" & RS.Fields("AudioIssues") &"'"
R"<td width=12 class=allprint>Play</td>"
// Call and play audio via JavaScript
$(document).ready(function()
{
var aElement = document.createElement('audio');
$('.Play').click(function()
{
if($(this).html() == "Play")
{
var waveFile = $(this).attr("data-waveFile");
var audioID = $(this).attr("data-audioId");
aElement.setAttribute('src', waveFile);
aElement.load()
aElement.addEventListener("load", function()
{
aElement.play();
$(this).html("Stop");
$(".duration span").html(aElement.duration);
$(".filename span").html(aElement.src);
}, true);
aElement.play();
$(this).html("Stop");
}
else
{
var waveFile = $(this).attr("data-waveFile");
var audioID = $(this).attr("data-audioId");
aElement.setAttribute('src', waveFile);
aElement.pause();
$(this).html("Play");
}
});
});

Make an onclick event react different when click second time

I have a button on my website, which plays the music when you click on it and in the same time it changes the text inside of the button (to "Go to SoundCloud".)
I want that button (with the new text on it) to redirect to SoundCloud when I click on it.
Now I got both when click first time, which is redirect to SoundCloud and play the track. (plus it changes the text)
Any ideas, how to solve this problem? Thx!
var links = document.getElementById("playButton");
links.onclick = function() {
var html='<iframe width="100%" height="450" src="sourceOfMyMusic"></iframe>';
document.getElementById("soundCloud").innerHTML = html;
var newTexts = ["Go to SoundCloud"];
document.getElementById("playButton").innerHTML = newTexts;
newTexts.onclick = window.open('http://soundcloud.com/example');
};
Use a variable that indicates whether it's the first or second click.
var first_click = true;
links.onclick = function() {
if (first_click) {
// do stuff for first click
first_click = false;
} else {
// do stuff for second click
}
}
Just redefine the onclick after the first function call.
Put the onclick on the button instead of the html.
document.getElementById("playButton").onclick=window.open('http://soundcloud.com/example');
Another option in some cases is to use a ternary operator and a boolean toggle expression:
let btn = document.querySelector('.button');
let isToggledOn = false;
btn.addEventListener ('click', function(e) {
e.target.textContent = !isToggledOn ? 'Is ON' : 'Is OFF';
isToggledOn = !isToggledOn;
});
newTexts.onclick is not creating a function to open a window, it is simply taking the return value of window.open which is being executed right away.
It should look like:
newTexts.onclick = () => window.open('http://soundcloud.com/example');
Also this will not work as intended because newTexts is not the actual DOM element, you need to attach the new onclick on the element and not the array...
But to other answers in this page, the logic is hard to read, so I'd advise to refactor the logic to be more readable.

Modify an OnClick handler in JavaScript

I have a call to an onclick that is already created before.
The button already has an onclick, but I need to add one more parameter before it does the submit.
Here's the View Source Code on the button:
<td valign='top' align='right' >
<button name="Complete" title="Complete"
onClick="document.forms.Maker.action='http://example.com:8080/internal/Step.jsp?theId=19032&target=step20&type=Full';
document.forms.Maker.submit();return false;">Complete</button>
</td>
This is a modification I made to add a confirmation after the user presses the button, and I also added so it shows what the onclick currently has:
function addEventConfirmation(element, type){
var old = element['on' + type] || function() {};
element['on' + type] = function () {
if (confirm("Are you sure?")){
old.call(this);
alert(old);
} else { return false; }
};
}
This is the alert from the before code:
function onclick()
{
document.forms.Maker.action='http://example.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full';document.forms.Maker.submit();return false;
}
The result should show something like this:
function onclick()
{
document.forms.Maker.action='http://example.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full&newParam=true';document.forms.Maker.submit();return false;
}
Try this: make the action value a variable.
var oldURI = "http://mysite.com:8080..."
var href = "oldURI" + "&newParam=true"
document.forms.Maker.action='href'
If this Html is your own code, do just like this :
document.getElementById('Complete').onclick = function()
{
document.forms.Maker.action=
'http://mysite.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full&newParam=true';
document.forms.Maker.submit();
return false;
}
else if you are trying to change this event handler from others website do this :
put website in an iframe named 'myframe' and code like this :
document.getElementById('Complete').onclick = function()
{
document.forms.Maker.action=
'http://mysite.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full&newParam=true';
document.forms.Maker.submit();
return false;
}
but remember to turn cross-domain data source access restriction of your browser off !!!
for example in ie :
Internet Options -> Security -> Custom Settings (Internet Zone) ->
Enable Access data sources across domains

Categories

Resources