Is there a function that gets triggered when an element is rendered? - javascript

Is there some sort of on render function in jQuery. I'd like this function to get triggered whenever a new element with the specified class or ID is added on the screen, either on the page load, or after AJAX requests that return HTML.
Edit: I want a callback that fires whenever a new element with the class or ID that I've defined is created. Not when something changes. I'd prefer not to use a plugin.

mmmmm.....
My Advice :
Create a Factory function of Creation of elements .
Every time you want to create an element ,
pass it through a centrelized function WHICH create the element.
She will have prameter of "what to create"
and she will create it.
then , put your code for "after creating element" in the same func

There is a new event for that but as usual it won't work for < IE9:
<head>
<script type="text/javascript">
function AddTextToContainer () {
var textNode = document.createTextNode ("My text");
if (textNode.addEventListener) {
textNode.addEventListener ('DOMNodeInserted', OnNodeInserted, false);
}
var container = document.getElementById ("container");
container.appendChild (textNode);
}
function OnNodeInserted (event) {
var textNode = event.target;
alert ("The text node '" + textNode.data + "' has been added to an element.");
}
</script>
</head>
<body>
<div id="container" style="background-color:#e0d0a0; width:300px; height:100px;"></div>
<br /><br />
<button onclick="AddTextToContainer ();">Add a text node to the container!</button>
</body>

I'm solving it this way:
$('html').change(function() {
$('.element').each(function() {
// Do stuff.
});
});
This way I can have an array that keeps track of all my elements, and when a HTML change is triggered check if there are elements that are not in my array, thus new elements.

$(document).on('DOMSubtreeModified',function(){
// something changed
});
Maybe this works for you but I'm not sure if every browser supports this event.
EDIT: Even this event is deprecated. So you should not use it.
Quick overview about events available:
http://www.quirksmode.org/dom/events/#t18

Related

How to write callback for newly added element in DOM upon click action in javascript?

I have a button which adds new element to DOM. Now I want to write event listner for click on this new Element. But not able to do so because when page loads this element will not be in DOM. The code I have tried so far is
const initButton = document.querySelector(".wS .amr .amn .ams");
initButton.click() // this will add new element in DOM which will be async action
// now I want to perform following on newly added element
document.querySelector(".fX.aXjCH").setAttribute("style", "display:block");
document.querySelector(".aB.gQ.pE").click();
I need some callback mechanism so that I can execute the later code once the DOM is updated with new component. How can I achieve this? how can I make assure the DOM is updated? or is there any way I can write callback for the first click()?
Have the script tag just before the end body tag
Add readystatechange event like this -
after the append yo can access the newly added markup.
Note: this kind of appending child using in .innerHTML is not safe if the markup is coming from say a Database and can cause XSS unless we sanitize the str.
<body>
<ul id="ul_o">
<button class='wS amr amn ams'>WS </button>
<div class='container'>
</div>
</ul>
<script type='text/javascript'>
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
const initButton = document.querySelector(".wS.amr.amn.ams");
const container = document.querySelector(".container");
initButton.addEventListener('click', function(){
var str = '<p>something here</p>';
var temp = document.createElement('div');
temp.innerHTML = str;
container.appendChild(temp);
const span = document.querySelector("p");
console.log(span);
});
}
}
</script>
</body>

Double Click with jQuery

I'm trying to make my webpage alert text when an element has been double-clicked using jQuery. Here's my JS:
$("#dashboard-acrs-map").dblclick(function () {
alert("asdasdasdasd")
})
And HTML:
<div class="dashboard-acrs-map-div" id="dashboard-acrs-map"></div>
Am I doing something wrong? Because the alert doesn't come up...
Note: It seems to be working UNLESS the element (#dashboard-acrs-map) is created using JS. How can I fix this?
That pretty much has to be your selected element not existing. It is possible that the script runs before the element is loaded. Place the script at the end of the body for example to make sure this is not the case.
$("#dashboard-acrs-map").dblclick(function () {
alert("asdasdasdasd")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dashboard-acrs-map">
Element
</div>
Dynamic element creation example:
document.querySelector("button").onclick = () => {
var element = document.createElement("div");
element.id = "double-click-me"; // Who cares though?
element.textContent = "Double Click Me";
element.ondblclick = () => alert("Double!"); // Hook up double click here.
document.body.appendChild(element);
};
<button>Create Double-Clickable</button>
(Furthermore, i believe that jQuery should never be used.)

Why I can't define a DOM element as a global variable?

I'm working on a form and wanted to use Javascript to output the form input.
So I have following script:
<script>
function showName() {
var box = document.getElementById("lorem").value;
console.log(box);
}
showName();
</script> `
The code above works really well but I wanted the var box = document.getElementById("lorem").value; to be a global variable so that I can use it in other functions without re-declaring it.
So when I have this it doesn't output anything:
`
<script>
//Declared outside the function
var box = document.getElementById("lorem").value;
function showName() {
console.log(box);
}
showName();
</script>
Please, what am I doing wrong?
You can use the same. it is not a problem. if you are still getting the null error, I would suggest to add the script at the end of the document or enclose it in a document.addEventListener("DOMContentLoaded", function(event) { block like below
document.addEventListener("DOMContentLoaded", function(event) {
var box = document.getElementById("lorem").value;
function showName() {
console.log(box);
}
showName();
});
<input type="text" value="hai" id="lorem"/>
The value of box is the initial value of your lorem element when you declare it. What you probably want is this:
var box = document.getElementById('lorem');
function showName() {
console.log(box.value); // <-- get the current value
}
// Outputs the current value, initially it will be empty
// of course, until you change your input and call the
// function again
showName();
Edit: the DOM needs to be loaded for this to work so make sure to put your script tags last in your <body>
You can either put the script all the way at the end before you close the <body> tag, or do as #jafarbtech suggested and add an event listener to wait for the DOM content to load.

onclick event handler in javascript code, not html tag

when trying to ensure my webpage is using unobtrusive javascript I cant seem to get the onclick event to work in my javascript, it only works as an event in the html tag. here is the code
var dow = document.getElementById("dowDiv");
dow.onclick=function () {}
any reason that this isnt working for me? as all the answers i can find say this is the way to do it, thanks in advance
There could be several reasons based on the information provided.
Most likely, the event function code is being attached before the DOM has finished loading.
Alternatively, you might be using a browser which doesn't support onclick (though this is unlikely!). To guarantee it will work, you can use fallbacks for the main routes of attaching an event:
if (dow.addEventListener) {
dow.addEventListener('click', thefunction, false);
} else if (dow.attachEvent) {
dow.attachEvent('onclick', thefunction);
} else {
dow.onclick = thefunction;
}
Make sure that you only have one element with the id dowDiv. If you have z-index's on elements and something is over the div it might be blocking the click event on the div.
var dow = document.getElementById("dowDiv");
var out = document.getElementById("out");
var clickCount = 0;
dow.onclick = function() {
clickCount += 1;
out.innerHTML = clickCount
}
<div id="dowDiv">Hello onclick <span id="out"></span>!</div>
You can use jQuery to achieve a simple o'clock function.
Make you include jQuery BEFORE you reference your .js file:
<script src="path/to/jQuery.js"></script>
<script src="file.js></script>
With jQuery you can say
$('#dowDIV').click(function(){
Do stuff here;
})

jQuery - how to determine which link was clicked

I have a simple piece of PHP which generates n copies of the following code:
<p class="ShowSDB_L2" class="center" onClick="FSD_L2('<?php print dbG;?>','<?php print $sLID;?>')">Click Here to See Data</p>
<div class="divSDB_L2">
</div>
It is generated using PHP, so the number of copies is unknown up front.
On another page I have the following Javascript (using jQuery)
function FSD_L2(dbG,SlID)
{
$(".divSDB_L2").load("test15.php?dbG="+dbG+"&SlID="+SlID).css('display','block');
}
When the text above (Click Here to See Data) is clicked, it should add the contents of test15.php between the the two DIV tags.
#Test15.php
<?php
$dbG = $_GET['dbG'];
$SlID = $_GET['SlID'];
print $dbG . " & " . $SlID;
?>
The problem I have is how to determine which of the links was clicked? At present, if I have three copies, and click one, all three copies are activated.
I hope I have made this clear enough. I'm sure there must be a simple way, but I'm quite new to Javascript/jQuery.
Like Brian said, you could just put the same class on all of your links and use the $(this) keyword in jQuery inside of a click function to find out which link was clicked.
Here's a basic example of changing link colors on a nav using this technique: http://jsfiddle.net/9E7WW/
HTML:
<a class="nav">Test</a>
<a class="nav">Test2</a>
<a class="nav">Test3</a>
<a class="nav">Test4</a>
Javascript:
$(document).ready(function(){
$('.nav').click(function(){
// change all to black, then change the one I clicked to red
$('.nav').css('color', 'black');
$(this).css('color', 'red');
});
});
Am not sure I fully understand what it is you are having difficulty with, but the following is how I would do it.
<p class="ShowSDB_L2" class="center" data-dbg="<?php print dbG;?>" data-slid="<?php print $sLID;?>">Click Here to See Data</p>
<div class="divSDB_L2"></div>
$(document).ready(function() {
$(document).on('click', 'p.ShowSDB_L2', function(evt) {
var $p = $(evt.currentTarget),
dbG = $p.data('dbg'),
slid = $p.data('slid'),
$div = $p.next();
FSD_L2(dbG, slid, $div);
});
});
function FSD_L2(dbG, SlID, $div)
{
$div.load("test15.php?dbG="+dbG+"&SlID="+SlID).css('display','block');
}
The click handler is not hardcoded to each p tag. Instead with each p tag we store the required data, ie dbg & slid.
The click handler is then attached once at document ready. jQuery abstracts over the various browsers and passes to its handlers the event object as its first parameter. This object can then be used to find the element on which the event occurred. Refer: http://api.jquery.com/on/
Finally, we fetch the required data from the clicked element, find the div that needs to be updated and then call your custom function.
Here is a cross-browser way to find the element (target) that triggered the event (e):
function getTarget(e){
// non-ie or ie?
e=e||window.event;
return (e.target||e.srcElement);
};
Add the complete URL to your link (or p in this case) using a data attribute:
<p class="ShowSDB_L2" class="center" data-loadurl="test15.php?dbG=<?php echo $dbG; ?>&SlID=<?php echo $SlID; ?>">Click Here to See Data</p>
<div class="divSDB_L2"></div>
Then do all the binding directly in your jQuery so you have direct access to the link that was clicked:
$(document).ready(function() {
$('.ShowSDB_L2').on('click', function(e) {
e.preventDefault();
$('.divSDB_L2').empty().load($(this).data('loadurl')).show();
});
});

Categories