I am trying to hide a div the id of which I stored in a variable named 'post_container_id'. My code is:
document.addEventListener('DOMContentLoaded', function() {
// Add event listener to following button
document.querySelectorAll('.post-edit').forEach(item => {
var itemid = item.getAttribute('id').slice(5,)
item.addEventListener('click', () => edit_post(itemid));
})
});
function edit_post(itemid) {
var post_container_id = `#post-container-${itemid}`;
(function(){
$(post_container_id).hide(1000);
});
};
This does not hide the div. It does not throw any error either. The function does get triggered (I checked it by logging to console). What am I doing wrong?
There is a mistake here:
(function(){
$(post_container_id).hide(1000);
});
You are just declaring the function, you should also call it:
(function(){
$(post_container_id).hide(1000);
})();
Also, the callback is useless in this case, you can just solve it as:
function edit_post(itemid) {
var post_container_id = `#post-container-${itemid}`;
$(post_container_id).hide(1000);
};
$("#hide").click(function(){
edit_post(1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="post-container-1">secret</div>
<button id="hide">Click to hide</button>
You can also use vanilla JavaScript to hide/show the element directly by changing the style display property. As follows
function edit_post(itemid) {
const post_container_id = document.querySelectorAll(`#post-container-${itemid}`);
post_container_id.style.display = 'none';
};
Without jQuery,
document.getElementById(post_container_id).style.display = "none"
Related
In my HTML, this works
<div id="portfolio1" onclick="changeMainFrame('lib/portfolio1.html')">
to trigger the following function:
function changeMainFrame(srcURL){
var target = document.getElementById("mainFrame");
target.src = srcURL;
}
I want to migrate it to my javascript doc. But this does not work:
document.getElementById("portfolio1").onclick = changeMainFrame("lib/portfolio1.html");
I can not find out how to fix this. Any hints? Cannot find a similar situation anywhere for something so simple yet time consuming.
document.getElementById("portfolio1").onclick = function() {
changeMainFrame("lib/portfolio1.html");
}
You're calling the function changeMainFrame. What you want to do is supply a function wrapper.
document.getElementById("portfolio1").onclick = function() {
changeMainFrame("lib/portfolio1.html");
}
function changeMainFrame(txt) {
alert(txt);
}
<div id="portfolio1">Click Me</div>
You need to assign a function to document.getElementById("portfolio1").onclick which will be called when that element gets clicked. The problem is that instead of assigning a function, you assigned the result of invoking/calling that function. What you can do instead is provide a function in which inside it you call changeMainFrame:
document.getElementById("portfolio1").onclick = function() {
changeMainFrame("lib/portfolio1.html");
};
You need to either use .onclick or the onclick attribute. Both of them require a handler function, and what you were passing was just the result of running your changeMainFrame function (null). Wrapping it in a function() { } yields your expected result.
function changeMainFrame(srcURL){
var target = document.getElementById("mainFrame");
target.src = srcURL;
}
document.getElementById("portfolio1").onclick = function(){changeMainFrame('https://codepen.io')}
<div id="portfolio1">go to codepen.io</div>
<iframe id="mainFrame" src="https://example.com"></iframe>
I have a function defined as follows:
window.onload = function() {
var ids = document.getElementById("idname");
function myFunction(){
/...*use ids var in here*./
}
}
I am trying to call myFunction from button onclick in html:
<button onclick="myFunction();"></button>
But it says myFunction is not defined. I understand because this is inside window.onload. How can I fix this? I need window.onload because I need to use document.getElementById("testID") to get content.
I need window.onload because I need to use document.getElementById("testID") to get content
No, you don't need window.onload. You simply have to put the code somewhere after the element with ID testID in the document.
Example:
<div id="testID"></div>
<script>
var ids = document.getElementById("testID");
function myFunction(){
/...*use ids var in here*./
}
</script>
However, if you want to keep using window.onload, then I suggest to not use inline event handlers, but bind the handler with JS:
window.onload = function() {
var ids = document.getElementById("testID");
ids.onclick = function(event){
/...*use ids var in here*./
}
};
(that might be a good thing to do anyway).
Lastly, you can get the a reference to the element inside the event handler using this or event.target:
<div id="testID"></div>
<script>
document.getElementById("testID").onclick = function(event) {
// access element via `this` or `event.target`
};
</script>
Learn more about event handling.
You defined it within a function so it's locked to that scope. Maybe you want to define it outside of that:
function myFunction() {
var ids = document.getElementById("idname");
// ...
}
window.onload = function() {
// ...
}
As a note, this is extremely old-school JavaScript. You could clean this up considerably using something like jQuery which would look something like this:
$(function() {
// Any initialization after page load.
});
function myFunction() {
var ids = $('#idname');
// ...
}
I know my question have answer in the past but I don't have the vocabulary to find this.
I call a JavaScript function like this:
Voir +
This function change the state of the element .stats-table but I want to know which button have been clicked to call this function?
Better : can I have a jQuery object of this button?
Try to pass the this reference to know which button was clicked,
HTML:
Voir +
JS:
function showTable(selec,elem){
var currentElem = $(elem); //Clicked element
}
If you don't want to change the signature of the function and the way you invoke it (as others have suggested), you can use the global window.event to identify the clicked element:
function showTable(selector)
{
var clickedElement = window.event.target;
//...
}
See MDN.
When you use jQuery, you might consider refactor your code like this:
$(document).ready(function(){
$('.show-table-link').on('click', function(){
var $usedButton = $(this)
showTable('.stats-table')
}
})
Voir +
It's good practice to attach the on click handler instead of writing it inline. Further reading document.ready and jQuery event basics.
You can pass any value or id and your can identify the function
<script type="text/javascript">
function showTable(clss_name,fun_id)
{
if(fun_id=='A1')
{
alert("First function Executed");
}
if(fun_id=='A2')
{
alert("Second Function is executed");
}
}
</script>
......
......
......
Voir +
Voir2 +
If your function is like this:
function showTable(selec) {
// some code
}
You can get the clicked element like this, using this:
function showTable(selec) {
// some code
var clickedElem = this;
}
I'm trying to do a simple image swap, but when I add in my code for the swap, it doesn't work! I have a function toggling different classes which are animated using CSS which work fine without the image swap code, but once I add it in all of it breaks!
Could someone troubleshoot my code really quickly? I feel like my JQuery logic is a bit off.
jQuery(document).ready(function () {
var toggle = 0;
var toggleClass = function () {
toggle = !toggle;
$(".two").toggleClass("two-menu", toggle);
$(".four").toggleClass("four-menu", toggle);
$(".images").toggleClass("images-menu", toggle);
$(".home").toggleClass("home-menu", toggle);
$("#bottom-left").toggleClass("bottom-left", !toggle);
$("#bottom-right").toggleClass("bottom-right", !toggle);
$("#margin-zero").toggleClass("margin-zero", !toggle);
$(".left-container").toggleClass("left-container-show", toggle);
$(".right-container").toggleClass("right-container-show", toggle);
}
var imageSwap = function () {
this.src = '/wp-content/uploads/2013/11/Twitter.jpg';
}, function () {
this.src = '/wp-content/uploads/2013/11/Facebook.jpg';
}
jQuery(".home").click(function () {
toggleClass();
});
jQuery(".two").click(function () {
toggleClass();
imageSwap();
});
jQuery(".four").click(function () {
toggleClass();
});
});
I've created two JSFiddles.
1) The first does not work, and includes the imageSwap function. http://jsfiddle.net/MuQ2w/
2) The second does not have the imageSwap, and works perfectly. http://jsfiddle.net/E2Rzv/
The problem you are experiencing is because of the syntax of you jQuery imageSwap function, as you can't write two function seperated with a "comma".
I think a possible solution might be to remove the second function.
Also imageSwap function doesnot know about 'this' as it is out of it's scope. You'll need to pass 'this' as an argument to it.
So the final imageSwap function will look like:
var imageSwap = function ($this) {
$this.src = '/wp-content/uploads/2013/11/Facebook.jpg';
}
And your call to this function would be like:
jQuery(".two").click(function () {
imageSwap(this);
toggleClass();
});
I hope it will help.
P.S. Just to follow the tradition, here is a working fiddle:
jsfiddle.net/gKxLz
did you look in your console for the errors? `
var imageSwap = function () {
this.src = '/wp-content/uploads/2013/11/Twitter.jpg';
}, function () {
this.src = '/wp-content/uploads/2013/11/Facebook.jpg';
}
is not correct syntax: the second function has no variable name
It is hard to figure out what is happening without debugging the code.
I am guessing that perhaps the problem is due to the scope of "this" inside imageSwap function.
Try to pass this (for the handler) to imageSwap function as a parameter, like:
var imageSwap = function ($this) {
$this.src = '/wp-content/uploads/2013/11/Twitter.jpg';
}, function ($this) {
$this.src = '/wp-content/uploads/2013/11/Facebook.jpg';
}
jQuery(".two").click(function () {
toggleClass();
imageSwap(this, this);
});
Hope it will work
I want to run a function after a link has been clicked.
The link I would like to point to the function is the one with the cancelLink class. The first link is here to show you as an example how I'm getting the AppointmentId the first link works by passing a parameter to another page.
I would like to be able to click the Cancel link and run a function on the current page.
Here are my links:
Invoice |
<a href="#" class="cancelLink" data-attr=${AppointmentId}>Cancel</a>
Below is my click function which is under the document ready:
$('a.cancelLink').click(function () {
var appointmentId = $(this).attr("data-attr");
//var appointmentId = $(this).attr("appointmentId");
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function () {
window.location = 'AppointmentViewAll.aspx';
});
});
Currently code does not enter this click function, how could I achieve this?
Your code seems fine to me. Here is a working plunk. Have you tried put a 'console.log("sample test");' inside your click handler to see if it's firing? Could you please also post how did you wrap your code inside $(document).ready() ?
Did you do it this way?
$(document).ready(function() {
$('a.cancelLink').click(function () {
var appointmentId = $(this).attr("data-attr");
//var appointmentId = $(this).attr("appointmentId");
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function () {
window.location = 'AppointmentViewAll.aspx';
});
});
});
try this:
$('a.cancelLink').click(function (e) {
e.preventDefault();
var appointmentId = $(this).attr("data-attr");
//var appointmentId = $(this).attr("appointmentId");
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function () {
window.location = 'AppointmentViewAll.aspx';
});
});
i hope it helps.
I found a few possible causes, see my comments;
HTML
Invoice
Cancel // Use quotes
Javascript
$(document).ready(function() { // Only access elements once the DOM is loaded
$(document).on('click', 'a.cancelLink', function(event) { // Try using on() instead of click() as you seem to be using some templating for creating the link ("${AppointmentId}").
event.preventDefault(); // DonĀ“t follow the link to #
var appointmentId = $(this).data('attr'); // Use data() instead of attr()
console.log(event.type, appointmentId); // View your console
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function() {
window.location = 'AppointmentViewAll.aspx';
});
});
});
See on() and data().
Use the onclick method to call a function and add parameters.
Cancel
function bindCancel(appointmentId) {
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function () {
});
}