Add class to dynamically added element [duplicate] - javascript

This question already has answers here:
jquery .load( ) and trigger function AFTER new content loads? just like JavaScript onload event
(3 answers)
Closed 8 years ago.
I have a shared left menu in a separate file from my pages so that I can update it in one place.
I am loading it onto the page in a .js file like so:
$(function () {
$("#left-nav").load("templates/left-nav.html", function() {
...
});
...
}
I would like to be able to set the nav-list item for the page to be selected. Something like this:
$("#calendar").addClass("selected");
...where #calendar is the ID of a list item in my left-nav.html template file.
Everything I've read says that I have to call addClass as a callback after I load in the file, but the following doesn't seem to work:
$(function () {
$("#left-nav").load("templates/left-nav.html", function() {
$("#calendar").addClass("selected");
});
...
}
Question: Is it possible to add classes to dynamically added content on a page, and if so, how should I do it? Thanks!

The code is correct as written, adduming that left-nav.html does contain an element with the ID of calendar.
The completed event is fired after the HTML is added to the DOM according to the jQuery documentation.

Related

How do I continue executing my .js code after programmatically adding jQuery to the DOM? [duplicate]

This question already has answers here:
How to include jQuery dynamically in any website using pure javascript
(9 answers)
Closed 25 days ago.
How do I continue executing my .js code after programmatically adding jQuery to the DOM?
The 3rd answer in this post shows how to add jquery to the dom but how should you continue executing further code?
For example you can't just add code underneath the self invoked function because jQuery hasn't yet loaded. How do I continue writing my .js code so that it executes?
$(window).on('load', function() {
// jQuery hasn't yet loaded so can't use this yet.
});
Execute the code that requires jQuery in the script's load event listener.
var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
jQueryScript.addEventListener("load", function() {
$(document).ready(function() {
...
});
});
document.head.appendChild(jQueryScript);

I want to show hide data via js on fetched data [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I have two pages, first page is having html now i am calling first page html on the second page via jquery and the code is given below.
$(".cat_ring").click(function(){
var x =$(this).val();
var alphabet=$('.soganii').val();
$.ajax({
url : '******************',
method : 'POST',
data : {id:x, alpha:alphabet},
success : function(data){
$(".soganiiiii").html(data);
}
});
});
now the html part which i am fetching from previous page to new page having one radio button. by which i want to show & hide a div. which i am trying to do by below code.
$('.custom').click(function () {
alert();
$('#product').show('fast');
});
$('#product1').click(function () {
$('#product').show('fast');
});
i can show the previous page html content to new page but my js is not working when i want to use radio button of fetched content.
Thanks in advance
You need to delegate your events because you have dynamically added elements
$('.soganiiiii').on('click','.custom',function () {
alert();
$('#product').show('fast');
});
$('.soganiiiii').on('click','#product1',function () {
$('#product').show('fast');
});

Load images before jQuery function ask for them [duplicate]

This question already has answers here:
Preloading images with jQuery
(20 answers)
Closed 6 years ago.
In my wordpress site i am using a quite simple jQuery piece of code:
jQuery(".first-sq").mouseenter(function(){
jQuery(".first-sq img").attr('srcset', '/wp-content/uploads/2017/01/MachineLearning_hoverx2.png');
})
jQuery(".first-sq").mouseleave(function(){
jQuery(".first-sq img").attr('srcset' , '/wp-content/uploads/2017/01/MachineLearningx2.png');
})
Now the code works but the problem is when mouseenter called it takes some time for the image to load, and you can see it being loaded. or in other words, the image revealed in portions. Is there a way to load all the images the document might use ,when document load, so when in situations like my mouseenter the image will show immediately and wont have to load?
You could achieve this by preload images. Try something like that:
$(document).ready(function () {
$('<img src="/wp-content/uploads/2017/01/MachineLearning_hoverx2.png">');
$('<img src="/wp-content/uploads/2017/01/MachineLearningx2.png">');
});
Copy of this
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
preload([
'img/img1.jpg'
]);

Difference between 'onclick's within javascript vs. html [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
<script type="text/javascript">
function translateIt() {
Microsoft.Translator.Widget.Translate("en", "es");
}
</script>
<button onclick="translateIt()">Translate</button>
<script type="text/javascript">
document.getElementById("btn").onclick = function () {
Microsoft.Translator.Widget.Translate("en", "es");
}
</script>
<button id="btn">Translate3</button>
This html block contains two buttons that should perform the exact same function. As such, the top button works but the bottom button doesn't. What is the difference between the 'onclick' implementation within html vs. within javascript?
The difference isn't with the click handler, the difference is the order of execution. In the first example you define something (the function) then reference it (in the HTML). In the second example you reference something (the HTML element) and then define it.
So in the second example the call to getElementById("btn") doesn't find anything, because at the time it executes that element doesn't exist yet.
HTML and JavaScript execute in the order in which they exist on the page as the page is being rendered. From the top of the document to the bottom.
If your second script example appears before the button, the getElementById will find no element.
By moving the script tag to after the element, it will work like normal.
<button id="btn">Translate3</button>
<script type="text/javascript">
document.getElementById("btn").onclick = function () {
Microsoft.Translator.Widget.Translate("en", "es");
}
</script>

AJAX based page needs repetitive javascript actions

I'm working on an application that uses JQuery layouts and loads only website parts (like Gmail). Every time I load a "panel" using JQuery I have to substitute some links to make it work with panels (i.e., to load this link content in a panel, not in the full page). Is something like this:
function changeMainPane(href) {
$("#screen").load(href);
$("#screen a.ajax-page").click(function () {return
changeMainPane($(this).attr("href"))
});
}
This is a very simplified changeMainPane function, mine has tens of $("#screen ...").click() calls to integrate the new piece of HTML into the page.
The question is: there is any better way to do this? Something like:
$("#screen").ready(function() {
// All my html setups
}
Or something like "always a user clicks on a link, check if has ajax-page class and the call this function" without having to initialize each link independently.
You can have a look at the delegate method. The delegate method can be registered for the common parent element of all the links on which you wants to reload the main panel. It can be the document object or a lower level element like "body" or another div like "div.mylinks".
$(document).delegate("a.ajax-page", "click", function(){
changeMainPane($(this).attr("href"))
})
Maybe jQuery live() is what you're looking for. You use it like this:
$("#screen a.ajax-page").live('click', function () { whatever; });
Then you don't need to reinitizalize after ajax activity.

Categories