I have this code here:
$(document).ready(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('Hello'); });
});
The weird thing I can't explain is, that when I execute the selector once I'm in the console when reaching the debugger statement, it returns an empty array, []
But when I step out and go on the page, then hit Ctrl-Shift-C in Chrome to start inspecting and click on some of the div's that have the ID I'm looking for then execute the selector again in the console, now I have the elements I'm expecting.
I have even tried this here so to validate whether it was an async. loading issue (this is a system over which I don't have all the control). but still, when reaching the debugger, the selector doesn't work - even after waiting 10 seconds (which then I'm pretty sure the div's are there). I still have to go in inspector so jQuery recognize the elements.
$(document).ready(function() {
//debugger;
setTimeout(function() {
debugger;
$("div[id^='stage_']").click(function (e) { alert('allo'); });
}, 10000);
});
Why would jQuery only be aware of elements that I've clicked on with Chrome's inspector ?
I know it's a bit late but when you open Dev Tools in Chrome the execution context is set to top. If your controls are located within an iFrame, that is a different context, not accessible from top. Use the dropdown to select your iFrame's context and your jQuery will return an element.
The reason it works when you inspect an element, is Chrome has selected the execution context for you already.
Discussion about iFrame context in Dev Tools
Using the "on", it works even if the element exists after the page loads.
$(document).ready(function(){
//$("div[id^='stage_']").click( function (e) { alert('Hello'); });
$("body").on('click','div[id^="stage_"]', function (e) { alert('Hello'); });
$('body').html('<div id="stage_1">teste1</div>' +
'<div id="stage_2">teste2</div>' +
'<div>blabla</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
doc: http://api.jquery.com/on/
Related
I have a page with two frames on it, and I have managed to respond to reloads of one of these frames. In the handler for the reload, I am trying to select an item on the newly loaded frame using jQuery, like so:
$("frame[name=WorkArea]").on("load", function () {
console.log("Reloaded work area."); //this works fine
alert($("tr.hdr", "frame[name=WorkArea]").html());
});
The alert box says "undefined." When I experiment at console to 'select everything',
$("*", "frame[Name=WorkArea]")
only one item is listed: the raw html of the frame.
So basically I can't select anything within the frame. It looks like the DOM is not yet constructed for the HTML contents of the frame (?) What am I missing?
PS Not sure this is relevant, but it's within an injected content script for a Chrome extension.
Try this,
$("frame[name=WorkArea]").on("load", function () {
console.log("Reloaded work area."); //this works fine
alert($(this).contents().find('tr.hdr').html()); // use this and find() here
});
Try with .find() in jquery
$("*").find("frame[name=WorkArea]").html();
or
$(document).find("frame[name=WorkArea]").html();
I'm trying to simulate a click in a tabbed div when the page loads.
To do this I use:
$(document).ready(function() {
$("#tab_inbox").click();
});
However, this doesn't seem to work, but when I enter this in the dev console on Google chrome, it does work..
$("#tab_inbox").click();
To show the tabs, I use this code:
$("#tab_inbox").click(function() {
$("#othertab").hide();
$("#tab_inbox").show();
});
Anybody knows what's wrong?
Try this:
$(document).ready(function() {
setTimeout(function () {
$("#tab_inbox").trigger('click'); //do work here
}, 2500);
});
I read in your comment that you're using show/hide techniques and I assume you need the click for an initial display option? If so, hide (or show) your element(s) specifically in the code rather than saying click to hide/show. So
$(document).ready(function() {
$("#tab_inbox").hide();
}
Or try core JavaScript and use
window.onload = function() {
// code here
}
window.onload waits until everything is loaded on your page, while jQuery's .ready() may fire before images and other media are loaded.
you can try making your own function with pure JS:
document.getElementById('triggerElement').addEventListener('click', funtction(e) {
document.getElementById('hideElement').style.display = 'none';
document.getElementById('showElement').style.display = 'block';
}, false);
Several problems:
1) I am trying to make this script run more efficiently.
2) When the user clicks either pop out button it opens a windows and hides the element. (Currently I am using .detach() to remove the embedded video player because in Firefox .toggle() just hides the player but keeps the audio playing. Is there a better way to do this?
3) In theory by clicking the button again or closing the window manually it should un hide or .toggle() the element but does not for the video player due to detach().
4) If a user pops out the window manually closes it and then pops it out again to only close it once more the element does not .toggle() back.
See it in action here, http://www.mst3k.tv/.
$(document).ready(function() {
$('#lights').click(function(){$('#darkness').fadeToggle(500);});
$("#lights").toggle(function(){$("#lights").attr('id','lightsoff');},function(){$("#lightsoff").attr('id','lights');});
/**VIDEO**/
var videoWin;
$('#video-toggle').click(function(){
$('#video').fadeToggle(500);
$('#video').detach();
});
$('#video-toggle').click(function(){
if (videoWin && !videoWin.closed) {
videoWin.close();
return false;
}
videoWin = window.open(
$(this).attr('rel'),
'videoWin',
'width=600,height=480,toolbar=0,top=0,left=0,menubar=0,location=0,status=0,scrollbars=0,resizable=1');
return false;
}
);
var watchVideo = setInterval(function() {
if (videoWin.closed) {clearTimeout(watchVideo);$('#video').show(500)}
return false;
}, 1);
/**CHAT**/
var chatWin;
$('#chat-toggle').click(function(){
$('#chat').fadeToggle(500);
/*$('#chat').detach();*/
});
$('#chat-toggle').click(function(){
if (chatWin && !chatWin.closed) {
chatWin.close();
return false;
}
chatWin = window.open(
$(this).attr('rel'),
'chatWin',
'width=320,height=480,toolbar=0,top=0,left=601,menubar=0,location=0,status=0,scrollbars=0,resizable=1');
return false;
}
);
var watchChat = setInterval(function() {
if (chatWin.closed) {clearTimeout(watchChat);$('#chat').show(500)}
return false;
}, 1);
/*$("a.btn").fitText(1.2, { minFontSize: "6px", maxFontSize: "14px" });*/
});
It would be better if you created a jQuery plugin for your code so you can re-use it and avoid DRY. Here are a couple of options:
Plugin 1: jQuery popupWindow
Plugin 2: jQuery winPop
Also note that the closed property is not part of any W3C specification, however it might be supported across Browsers.
You could also write a JS function that could be reused. According to the w3cschools website the window.closed property is supported in most major browsers and you can check for it prior to triggering the event.
instead of
if(videoWin && !videoWin.closed)
you could use
if (typeof videoWin!='undefined'){ /* it has been created */}
elseif(typeof videoWin='undefined') { /*it's okay to open the new window*/}
Make sure you're not creating the variable if you're using this as a check though until the window open event has been fired. Since you're creating the var a couple of lines above your function declaration it will always return as defined.
You'll need to specify a target object in your function to have it throw multiple windows correctly... meaning you can't declare one var for multiple windows. Maybe a class would be better.
Something I thought was odd earlier but forgot to mention before FB posted my response prematurely was that you're adding your href in the rel attribute and specifying the href as a js:void(0) which is also non-standard. The rel attribute is for specifying the relationship between the link and the page... (eg. rel=nofollow). That might also be why it's not firing and misfiring some of the time as well, and the differences between browser response.
Recently I ran into a mysterious problem that IE (6-8) is keeping throwing me an error. I don't know if this is the problem, but I think it is.
Open up the F12 developer tools in a jQuery included website, enter
$(window).load(function(){
alert("Wont able to see me");
});
And an error will popup:
"Unable to get value of the property 'slice': object is null or undefined"
Did I do anything wrong, or anything else???
I recently found a work-around for IE not recognizing $(window).load()...
window.onload = function() {
alert("See me, hear me, touch me!");
};
This is a little different than $(function(){}) as it executes after all elements are loaded as opposed to when the DOM is ready.
I recently implemented this in another project and it worked wonderfully.
For anyone still running into this, IE11 (only one I tested) does not fire the the load event if the listener is inside of the jquery ready function. So pull the load function outside of the ready function and it will fire in IE11.
//this is bad
$(() => { //jquery ready
window.onload = () => { //wont fire in IE
cosole.log('window loaded');
}
});
//this is good
$(() => { //jquery ready
cosole.log('dom ready');
});
window.onload = () => { //will fire in IE
cosole.log('window loaded');
}
The latest jQuery (1.7.1) with IE10 and IE9 does not produce such an error for me.
As a side note; If you wish to execute something when the dom is ready;
Try this way;
$(function(){
alert("Wont able to see me");
});
I believe this is the standard convention for attaching a function to domready event.
Reference: jQuery Documentation
I am struggling with jQuery for a long time now. It is very powerful and there are lot of great things we can do with jQuery.
My problem is that I use a lot of jQuery features at the same time. E.g. I have a site that displays items, 12 items per page and I can paginate through the pages using jQuery. On the same page I implemented a thumpsUp button that uses jQuery too.
The more jQuery features I use, the harder it gets to arrange them properly. E.g.:
$(document).ready(function() {
$(".cornerize").corner("5px"); //cornerize links
$('a#verd').live('click', exSite); //open iframe
$("a.tp").live('click', thumpsUp); //thumps up
$("a#next").click(getProgramms); //next page
$("a#previous").click(getProgramms); //previous page
//for the current page reload the content
$("a#page").each(function() {
$(this).click(getProgramms);
});
//this isn't working...
$('.smallerpost').live('click', alert('test'));
});
Have a look at the last code line. I want to perform an alert when the div element is clicked. Instead of doing so the page shows me the alert when I refresh the page. A click on the div has no effect.
What am I doing wrong? What would be a strategy here to have clean and working jQuery?
Change that line to
$('.smallerpost').live('click', function () {
alert('test');
});
and while you're there...
$("a#page").each(function() {
$(this).click(getProgramms);
});
has exactly the same effect as:
$('a#page').click(getProgramms);
... but technically there should be only one element with id='page' anyway
Your code $('.smallerpost').live('click', alert('test')); calls the alert immediately and passes its return value into the live function as the second parameter. What you want to pass there is a function to call, so you want:
$('.smallerpost').live('click', function() {
alert('test');
});
or
$('.smallerpost').live('click', handleSmallerPostClick);
function handleSmallerPostClick() {
alert('test');
}
...depending on how you structure your code.