In my erb file, I have a script like this:
function checkJquery() {
if(window.jQuery) {
jQuery(document).ready(function() {
alert('onready');
$('div#habla_topbar_div').click(function() {
alert('onclick');
});
});
}
else {
window.setTimeout(checkJquery, 1000);
}
}
I get the 'onready' alert, but the 'onclick' alert does not work. Any idea what I might doing wrong?
Edit:
The div is part of the Olark chat integration and the erb file has nothing except the configuration for that and the above script.
The div 'habla_topbar_div' is defined.
Image:
Several Rails-specific issues here
--
Delegation
Because most Rails applications use Turbolinks or similar, you have to delegate your Javascript (typically) from the document object:
#app/assets/javascripts/application.js
$(document).on("click", "#habla_topbar_div", function() {
alert('onclick');
});
If you use this without embedding with other JS functions, it should work, considering you have a div with id=habla_topbar_div.
--
Turbolinks Events
Secondly, you want to ensure you replace the standard $(document).ready function with one of the Turbolinks event hooks. You'll want to do the following:
#app/assets/javascripts/application.js
var your_function = function(){
...
}
$(document).on("page:load ready", your_function);
Your code looks good, maybe you don't have a div with id="habla_topbar_div".
Check this Fiddle to find out where did you wrong.
Update:
If you already have a div with id="habla_topbar_div" maybe the Id's value has been changed by some code or application before rendering or on runtime.
Try to add an unique class name to "habla_topbar_div" div like this:
<div id="habla_topbar_div" class="habla_topbar_div_unique habla_topbar_div_normal ...">
and use this:
$('.habla_topbar_div_unique').click
instead of this:
$('div#habla_topbar_div').click
Check Fiddle Demo
Related
I load a part of my basketpage inside an accordion div in my header. This works great and shows my basket in a nice dropdown.
The last problem I need to solve with this is to get the buttons in the loaded content to work. Is it possible to write an callback that make these works? Im not sure even what to google for this one..
This is how the buttons is setup in the loaded content:
checkout
Script Im using to load the content:
$('.dcjqg-accordion ul.sub-menu').load('/m4n?seid=etailer-basket div#centerbox.itembox.centerbox');
use the callback function of .load().
$('.dcjqg-accordion ul.sub-menu').load('/m4n?seid=etailer-basket div#centerbox.itembox.centerbox', function() {
$("#_ec_oie2").on("click", function() {
if (UI.pb_boolean(this, 'click')) { }
return false;
});
});
checkout
You need to use a child selector for the event. You can attach an event to the .sub-menu element that will fire on the content loaded in through the ajax. Something like the following could work:
$(".dcjqg-accordion ul.sub-menu").on("click", ".action.actionbasket.checkout", function() {
if( UI.pb_boolean(this, 'click') ) {}
return false;
});
Notice the second parameter to the on method. It is a selector that will be used to look at the target of the click event. I used .action.actionbasket.checkout since that is what is on your a tag.
This code may not work exactly, but this should help get you in the right direction.
Here is the link to the jQuery documentation for the on method: https://api.jquery.com/on/
I have a need to add a class to certain pages - ones that contain an ID of #hero. For all other pages, the class must not be added.
Because I'm using asp.net with a few layered master pages, its not as simple as just adding a class directly to the html becuase the body tag sits a couple of pages above the aspx page.
I could locate the body tag, but so far I've tried to avoid that due to the added complexity, and instead tried to use jquery.
Here's the code:
$(document).ready(function () {
updateBodyClasses();
});
function updateBodyClasses() {
if($("#hero")) {
$("html, body").addClass("hero");
}
}
Nothing complicated, but here's the rub. By the time the class has been appended, the page has been rendered and the class doesn't seem to have any effect. However, if I test it by adding the class directly to the html, it works - so I know the CSS works and that its a timing issue.
I suppose I could add the code higher up the page - jquery is deferred, so I would need to know the equivalent javascript to try it out.
Would appreciate any thoughts on this potential solution, or perhaps and other ideas.
/* UPDATE */
For clarity, it seems to be the HTML related class that isn't being applied.
You can alter the DOM without waiting for it to be ready.
You need to:
load jQuery in a synchronous way(without defer or async).
Put #hero element i above the script.
Please consider this example:
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hero">I don't care about DOM being ready</div>
<script>
var $el = $('#hero');
if ($el.length) {
$el.addClass('red');
}
</script>
You can use IIFE(Immidiately Invocked Function Expression):
like:
(function()
{
if($("#hero")) {
$("html, body").addClass("hero");
}
})();
just put your function in document ready like
$(function(){
if($("#hero")) {
$("html, body").addClass("hero");
}
});
No real solution provided.
Not reasitic to change the whole site infrastructure - from one that defers jquery to loading it synchronously.
The two other jquery answers are as per the current setup and don't work.
The only working solution was provided by Tushar, although it would still require selective loading of the script, which was not included in the answer.
In the end, I used a workaround, which bypassed the need for any javascript. Instead of selectively adding a class to html tag, I added the css permanently to the html tag, affecting all pages. I then added an inner div, which reverses it out. This means that any page can now manipulate its own functionality directly without having to add classes to the html tag.
I'm using Phonegap to build a small (test only) Macrumors application, and remote hosts actually work (there is no same host browser restrictions). I am using the jQuery Load() function to load the contents of the Macrumors homepage http://www.macrumors.com/ into a bin, hidden div, then the each function to loop through all the article classes to show the title in a box with a link to the page.
The problem is, after the Macrumors HTML content is loaded, the each function doesn't work with the article class. Also, in the load function (which allows you to specify certain selectors, id's and classes included, to only load in those sections of the page) the class doesn't work; none of the classes do, in both the load function and each function. And many Id's don't work in the each function either.
Can anybody explain this to a noob like me?
Here is the code:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content');
$('.article').each(function(){
var title = $('a').html();
$('#content').append('<b>'+title+'</b>')
});
}
And the HTML stuff
<body onload="onBodyLoad()">
<div id="bin">
</div>
<div id="content">
</div>
</body>
I sincerely apologize if there's some very simple mistake here that I'm missing; I'm a major JS newbie.
.load() is asychronous. It hasn't completed yet when you're executing .each(). You need to put your .each() and any other code that wants to operate on the results of the .load() in the success handler for .load().
You would do that like this:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content', function() {
$('.article').each(function(){
var title = $('a').html();
$('#content').append('<b>'+title+'</b>')
});
});
}
I'm also guessing that your .each() function isn't working quite right. If you want to get the link out of each .article object, you would need your code to be like this so that you're only finding the <a> tag in each .article object, not all <a> tags in the whole document:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content', function() {
$('.article').each(function(){
var title = $(this).find('a').html();
$('#content').append('<b>'+title+'</b>')
});
});
}
I'd like to build onmouseover directly into a javascript block. I can do it within a hyperlink but I need to do it in the actual script section for the code im writing. Can I do object.onMouseOver()? Or is there another way to do it?
So for example I'd like
<script>
something i can put in here that will make on mouseover work on a specific object
</script>
Yes. :)
<span onmouseover="alert('Hi there')">Hi there</span>
Do you mean like that?
edited to add:
Ah I see so like this?
<span id="span1">Hi there</span>
<script>
document.getElementById('span1').onmouseover = function() {
alert('Hi there');
}
</script>
You bind events to HTML elements not javascript blocks. If you are talking about binding events to elements using script, yes you can do it. You can use addEventListener to bind events.
document.getElementById("eleid").addEventListener("mouseOver", myEventMethod, false);
Yes you can so if you have a link somewhere in the page that you want to fire the hover for you can use the following.
http://jsbin.com/asoma4/edit
EDIT: I should add that the attached is just an ugly example to demonstrate that what you want to do can be done. I would look into popular js libraries (jquery, prototype, etc..) to clean this up a lot and make it easier.
You can use addEventListener in Firefox/Chrome/etc. and attachEvent in IE. See this page.
For example,
<div id="cool">Click here!</div>
<script>
function divClicked()
{
// Do some stuff
}
var theDiv = document.getElementById("cool");
if(theDiv.attachEvent)
{
// IE
theDiv.attachEvent('onclick', divClicked);
}
else
{
// Other browsers
theDiv.addEventListener('click', divClicked, false);
}
</script>
If you want to avoid having to write all that code, you can use a JavaScript library (jQuery, Prototype, etc.) to simply your code.
This my javascript :-
<script type ="text/javascript">
$(function()
{
$("#tabs").tabs({ cache: true ,fx: { opacity: 'toggle' }});
});
</script>
And this is my html which loads php file using ajax :-
<ul>
<li>General</li>
<li>Messages</li>
<li>Pics</li>
<li>Facilities</li>
</ul>
The question i want to know is when Messages.php is loaded does the javascript onload event fire? I want to know because i want to take my textarea and convert it into editor. However i am not able to capture window.onload event :-
window.onload = function(){
alert('hello');
}
and further if i write something in :-
$(function(){
}
It works in Opera and IE but sometimes doesn't work sometimes. To sum, how do i capture window.onload in the above situation?
EDIT
Looks like $(function(){ } seems to be working, the problem is with fx: { opacity: 'toggle' }. When i remove effect, it works fine.
Thanks in advance :)
The window.onload event will not fire, in the document you're loading into it already fired earlier.
You should be able to use document.ready, e.g. $(function() { }); in the page you're fetching and it work, provided you're on at least jQuery 1.4.2+. Several issues were fixed with events in the 1.4.2 release, including one around this being inconsistent, if you're using 1.4.1 or below, I can't promise it being 100% consistent.
Alternatively, you can have the code in the main page instead of inside Messages.php and run the code in the load event of the tabs, like this:
$("#tabs").bind("tabsload", function(event, ui) {
$('.myEditorClass', ui.panel).myEditorPlugin();
});
I've noticed in some browsers that if you use display:none it won't render anything inside that tag, it just ignores whatever's in there because it's not being displayed. I'm not sure if that fx setting is using .hide(), but that could part of the issue.
Also why not set up a function on the loaded pages called "init", then have ajax do a callback to trigger it?