How do I get this code to work in the "head" tag of the HTML. I must use these two functions, and cannot use only one function. I know this is bad practice, but how would I go about doing this? Thank you for your help.
var myImage;
function prepareEventHandlers() {
var myImage = document.getElementById('mainImage');
}
function runEvents() {
myImage.onclick = function() {
alert('You clicked on the image.');
};
}
window.onload = function() {
prepareEventHandlers();
runEvents();
}
You need to remove var in prepareEventHandlers(), because you are declaring a new local variable called myImage, not assigning the outer one.
var myImage;
function prepareEventHandlers() {
myImage = document.getElementById('mainImage');
}
Remove the "var" in your prepareEventHandlers() function.
var myImage;
function prepareEventHandlers() {
myImage = document.getElementById('mainImage');
}
function runEvents() {
myImage.onclick = function() {
alert('You clicked on the image.');
};
}
window.onload = function() {
prepareEventHandlers();
runEvents();
}
Related
I'm having trouble triggering a function. I have the following code:
var dnfmomd;
dnfmomd = new function () {
//function content
}
$("#launch_button").on("click", dnfmomd.init);
Have you tried this?
var dnfmomd = function () {
//function content
}
$("#launch_button").on("click", dnfmomd());
I would recommend doing it this way
var dnfmomd = function() {
//function content
}
$("#launch_button").on("click", function() {
dnfmomd();
});
Function:
function abc()
{
$('#table_id tr td').removeClass('highlight');
$(this).addClass('highlight');
tableText($table_label,$table_id);
}
abc();
function refresh()
{
abc().hide; // Need help at this.
}
<button class="refresh" onclick="refresh()">Refresh</button>
I'm trying to remove function/stop running abc() function, when refresh button was clicked.
Try this code, if abc is in the global scope:
window.abc = function() {
return false;
}
or you could do: window.abc = undefined when it's in the global scope.
when it's a method: delete obj.abc
You can pass param in your function and check condition like below.
function abc(arg) {
if (arg) {
$('#table_id tr td').removeClass('highlight');
$(this).addClass('highlight');
tableText($table_label, $table_id);
} else {
//Do what ever you want if needed
}
}
abc(true);
function refresh() {
abc(false)
}
Put all the code you only want to run once at the start inside window.onload
window.onload = function() {
$('#table_id tr td').removeClass('highlight');
$(this).addClass('highlight');
tableText($table_label,$table_id);
}
Wrap the function inside an object to delete it. You can use the window object or create a new one. Example:
const functions = new Object;
functions.abc = () => { /* do something */ };
functions.abc();
const refresh = () => {
if ('abc' in functions){ functions.abc(); delete functions.abc; }
else { /* will do nothing */ }
};
Solved :-)
I think my javascript in my php file is in conflict with my javascript file.
I have a script that checks of the image is smaller then 2MB and a script that shows the image you selected in a small version. But the second part does not work when the first script is active. how do I fix this?
script in HTML
<script>
window.onload = function() {
var uploadField = document.getElementById("frontImages");
uploadField.onchange = function() {
if(this.files[0].size > 2000000){
alert("File is too big!");
this.value = "";
};
};
var uploadField = document.getElementById("itemImages");
uploadField.onchange = function() {
if(this.files[0].size > 200){
alert("File is too big!");
this.value = "";
};
};
}
</script>
.js file
$("#frontImages").change(function () {
if ($('#frontImages').get(0).files.length > 0) {
$('#frontImages').css('background-color', '#5cb85c');
} else {
$('#frontImages').css('background-color', '#d9534f');
}
});
$("#itemImages").change(function () {
if ($('#itemImages').get(0).files.length > 0) {
$('#itemImages').css('background-color', '#5cb85c');
} else {
$('#itemImages').css('background-color', '#d9534f');
}
});
document.getElementById("frontImages").onchange = function () {
var x = document.getElementById('previewFrontImage');
x.style.display = 'block';
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById("previewFrontImage").src = e.target.result;
};
reader.readAsDataURL(this.files[0]);
};
function previewImages() {
var $preview = $('#previewItemImages').empty();
if (this.files) $.each(this.files, readAndPreview);
function readAndPreview(i, file) {
var reader = new FileReader();
$(reader).on("load", function () {
$preview.append($("<img/>", {src: this.result, height: 100}));
});
reader.readAsDataURL(file);
}
}
$('#itemImages').on("change", previewImages);
I'm guessing that the conflict is between the html script and this
document.getElementById("frontImages").onchange = function ()
I also have a question how I can fix that there will be no small image when the image is too big
Your guess is correct, onchange is simply member variable of various elements, and thus
var uploadField = document.getElementById("frontImages");
uploadField.onchange = function() {
and
document.getElementById("frontImages").onchange = function ()
are setting this single variable (of frontImages), which will store one callback function at a time.
You could use addEventListener() instead, which maintains a list of event listeners, so there can be more than one. Modifying the lines to
var uploadField = document.getElementById("frontImages");
uploadField.addEventListener("change", function() {
and
document.getElementById("frontImages").addEventListener("change", function ()
will register both event listeners on frontImages, regardless of the order they are executed.
Side remark: when you have "nice" ids, document.getElementById() can be omitted, as elements with ids become variables (of window which is the global scope), and thus you could write frontImages.addEventListener(...). You still need the getter in various cases, like when a local variable shadows the id, or when it is not usable as variable identifier (like id="my-favourite-id" or id="Hello World")
I have two functions in jQuery. One of them looks for image extensions from form and another is getting image dimensions and triggers an alert() when an image is not big enough.
Both functions are correctly executed in demos but together only one is executed. Only part where extensions is getting is executed. Sorry for the length of the code but it was the only way to show the problem.
(function ($) {
$.fn.checkFileType = function (options) {
var defaults = {
allowedExtensions: [],
success: function () {},
error: function () {}
};
options = $.extend(defaults, options);
return this.each(function () {
$(this).on('change', function () {
var value = $(this).val(),
file = value.toLowerCase(),
extension = file.substring(file.lastIndexOf('.') + 1);
if ($.inArray(extension, options.allowedExtensions) == -1) {
options.error();
$(this).focus();
} else {
options.success();
}
});
});
};
})(jQuery);
$("#filput").on('change', function () {
var fr = new FileReader;
fr.onload = function () { // file is loaded
var img = new Image;
img.onload = function () {
// image is loaded; sizes are available
var w = img.width
if (w < 500) {
alert("too small");
} else {
alert("big enough");
}
};
img.src = fr.result;
};
fr.readAsDataURL(this.files[0]);
});
$(function () {
$('#filput').checkFileType({
allowedExtensions: ['jpg', 'jpeg', 'png'],
error: function () {
alert('error');
}
});
});
Only part where extentions is getting is executed
That code is wrapped by $(function() { ... }); so, you should probably put both pieces of code there:
$(function() {
$("#filput").on('change', function () {
var fr = new FileReader;
// ...
});
$('#filput').checkFileType({
// ...
});
});
Based on what you have described, the input element wasn't present yet at the time your code is run; by putting both code segments in the DOMReady event handler, you're making sure it exists.
The following code works, but I'd like to use the self-invoking function syntax when declaring it instead of calling it explicitly on the last line:
var ShowMe = function() {
if ($('input:checkbox:checked').length) {
$('#Save').fadeIn('slow');
} else {
$('#Save').hide();
}
};
$('input:checkbox').on('click',ShowMe);
ShowMe();
You can't declare the var inside of an expression, but you can put its definition in one:
var ShowMe; (ShowMe = function() {
if ($('input:checkbox:checked').length) {
$('#Save').fadeIn('slow');
} else {
$('#Save').hide();
}
})();
$('input:checkbox').on('click',ShowMe);
Try this instead:
var ShowMe = function() {
if ($(this).length) { // `this` is the input that was clicked
$('#Save').fadeIn('slow');
} else {
$('#Save').hide();
}
};
$('input:checkbox').on('click', ShowMe).trigger('click');
Update based on comments below:
$('#Save').hide();
$('input:checkbox').on('click', function() {
if(this.checked) { //check if this is checked
$('#Save').show('slow');
}
else if(!($('input[type="checkbox"]:checked').length)) {
//check to see if anything else was checked
$('#Save').hide();
}
});