Using browser to find the javascript code currently running - javascript

Is it possible to find the javascript code for current event using the console, on any browser?
For example, please see this JSFiddle. This is the corresponding code:
.close-icon {
border:1px solid transparent;
background-color: transparent;
display: inline-block;
vertical-align: middle;
outline: 0;
cursor: pointer;
}
.close-icon:after {
content: "X";
display: block;
width: 15px;
height: 15px;
/*position: absolute;*/
float:right;
background-color: #FA9595;
z-index:1;
right: 35px;
top: 0;
bottom: 0;
margin: auto;
padding: 2px;
border-radius: 50%;
text-align: center;
color: white;
font-weight: normal;
font-size: 12px;
box-shadow: 0 0 2px #E50F0F;
cursor: pointer;
}
<input type="range" min="12" max="120" id="slider" />
<div class="text" contenteditable="true" style="cursor:grab;">hello1<button class="close-icon dbutton" type="reset"/></div>
<div class="text text1" contenteditable="true" style="cursor:grab;">hello2<button class="close-icon dbutton1" type="reset"/></div>
<div class="text text2" contenteditable="true" style="cursor:grab;">hello3<button class="close-icon dbutton2" type="reset"/></div>
<div class="text text3" contenteditable="true" style="cursor:grab;">hello4<button class="close-icon dbutton3" type="reset"/></div>
$("#slider").on("change",function(){
var v=$(this).val();
$('.text.active').css('font-size', v + 'px');
});
$('.text').on('focus',function(){
$('.text').removeClass('active');
$(this).addClass('active');
});
$(document).on("click",".close-icon",function(){
$(this).closest('div').remove();
//alert('hiii');
});
Here I write the code to enlarge the text and close the div. Now is it possible to see the code responsible for resizing the text, when I am resizing the that text?
UPDATE : I know how to inspect element, change style and other things
. But here i am asking to know how to detect the javascript code or
function for the current event.Hi, it's not about console .log
function . I know this already . I am asking that how to know which
function is working when i click the close button , how can i see that
code in browser . Here i write the code , i understand where the code
is . What about if some other write the code and i am looking browser
for detecting what code and what event is running

You can run the console.log() function on the browser console in situations where it could return useful info for debugging. For example, if you add, on your script, console.log() as:
$("#slider").on("change",function(){
var v=$(this).val();
console.log(v);
...
});
Then open it in the browser and activate the inspector (shift + cmd + i on Chrome on the Mac, for example), and click on the Console tab: you should see the value of v changing.
Checking which code is responsible for specific tasks may be tricky. One way you can try is to, using Chrome, open the Console, click on the Sources tab, and click on the little pause icon (pause script execution). Then, when any javascript tries to run, Chrome will pause and show you the code. The problem with this approach is that many times there is a loop running constantly. And if that's the case, as soon as you press pause, Chrome will show you the line of javascript of that loop, and you won't have time to actually execute the action you're interested at finding the code for.
If you have an idea of which script is running, you can click the Sources tab, browse to the javascript file that has the code, and add a breakpoint. Then you can execute the action, and if the action involves that piece of code, Chrome will pause at that breakpoint. In the same tab (Sources), try to click the line number, and set "Never pause here". Even though this method won't help you out with every possible code you may be inspecting, sometimes it will.
Also on Chrome, use the console search (open console then cmd + alt + f on Chrome for Mac) to search through all the resources loaded on that page. If you know you're looking for a script that deals with a certain CSS class or id, you can search for this id or class, see if you can find it on a javascript resource, and add a breakpoint. When you get to that point, the script will pause, and you will be able to run commands on the console. If your break point was, say, in a class method, then you would be in the scope of that class method context.

You can use Inspect Element on Chrome by right click to see your code. Select source tab from the inspect window. Same way in Firefox too. Place a break in corresponding event. Using Firebug in Firefox will be better.

Update: examples attached.
To open DevTools hit Ctrl + Shift + I on windows then tab Console use examples below:
console.log("test");//add this were ever you want to test
//examples
Element.onclick = function(){
console.log("clicked");
}
Element.onkeyup = function(){
console.log("keyup detection");
}
window.onload = function(){
console.log("page loaded");
}
Also to catch error by line you can use
try{
var invalid = "hello world';//<===== here is invalid string
}catch(e){
console.log(e.stack);//catched error details (line, file, error)
}
is it possible see the code for resize the text when i am resizing the that text ?
Example to detect button click, focus and range change
Check Fiddle

Related

Why do separate "paste" event listeners both paste to the same <div>?

At least under the latest release of Chrome for Windows, the paste event listener is giving me inconsistent results.
I'm attempting to listen for paste events from two column divisions on the screen and allow the user to paste text to one column or the other depending on where he/she clicked last. For some reason, pasted text always goes to the righthand column.
It was noted that I could use <input> instead of <p> for this, but once the user pastes text I want my script to respond to clicked-on words of the pasted text and AFAIK <input> does not allow that.
Any experience, help, or workarounds appreciated, thanks.
Live Demo
Tested with Chrome, Version 63.0.3239.132, under Windows 7 Pro, Chromium latest release under Ubuntu.
Update, 1/12/18:
Following advice from #Grant (below), I inserted content into my two <div>s and Chrome began accepting paste actions for both of them. Moreover, Firefox, which had not been responding to paste actions anywhere in the window, now also began accepting
pasted text to both columns.
Meanwhile, the examples I've published here still hold true, and I would like to know why: is this "expected" behavior, or just an implementation problem with the paste event for these browsers?
// Listen for "paste" events in each column:
//
document.getElementById("leftColumn").addEventListener("paste", leftPaste, false);
document.getElementById("rightColumn").addEventListener("paste", rightPaste, false);
// todo: for some reason leftPaste() is not triggered:
//
function leftPaste(e) {
var clipboardData, pastedData;
clipboardData = e.clipboardData;
pastedData = clipboardData.getData('Text');
alert(pastedData);
document.getElementById('leftPara').textContent = pastedData;
}
function rightPaste(e) {
var clipboardData, pastedData;
clipboardData = e.clipboardData;
pastedData = clipboardData.getData('Text');
alert(pastedData);
document.getElementById('rightPara').textContent = pastedData;
}
body {
color : #334455;
background-color: #aabbcc;
font-family: 'PT Sans', sans-serif;
font-size : 14px;
cursor : default;
}
.frame {
border: 1px solid rgb(31, 40, 49);
background-color : #283849;
color : #aabbcc;
overflow: auto;
position: relative;
}
.myColumn {
height: 90vh;
overflow: auto; /*causes scrollbars*/
float: left;
width: 45%;
margin-left: 4%;
}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Text pasted to left column goes to right column</title>
</head>
<body>
<h3>With Google Chrome, Version 63.0.3239.132 (Official Build) (64-bit) under
Windows Pro 7 64 bit,
clicking and pasting in either column pastes to the right column.
</h3>
<div id=leftColumn class="myColumn frame">
<p id=leftPara style="word-wrap: break-word; white-space: pre-wrap;" class=clickable></p>
</div>
<div id=rightColumn class="myColumn frame">
<p id=rightPara style="word-wrap: break-word; white-space: pre-wrap;" class=clickable></p>
</div>
</body>
I couldn't definitively tell you why this behaviour is this way - maybe someone smarter can, but I have encountered situations before where a div needs to actually have content within it for that div to be focusable. Here is a pen demonstrating the desired outcome: https://codepen.io/anon/pen/QaQBPV. - The text "Left." and "Right." makes it focusable individually.
<div id=rightColumn class="myColumn frame">
Right <!-- this bit -->
<p id=rightPara style="word-wrap: break-word; white-space: pre-wrap;" class=clickable></p>
</div>
The event firing on the parent div when wrapping the divs is due to something called event bubbling, which you had set to true, I changed that to false in the pen (the last parameter in the event listener) - see http://alistapart.com/article/domtricks2 for more info.

element unvisible until developer console opened

I've got a website where some LayerSlider elements stay invisible until
the window is resized
I disable the Bookmarks bar in Chrome (whaaat ?)
I switch on Chrome debugger tools
The issue also appears in Firefox and Safari on OS X (all on the newest versions).
I have no idea what that could be. To me it looks like some OS render issue.
I am looking for a workaround.
How can I trigger some kind of repaint after pageload that will unhide those elements? (same thing that happens when I open the dev console for instance)
I tried jQuery(document.body).hide().show(); but that doesn't work.
There is bit more info to it:
The image is hidden because it is scaled to zero height and with after the initial load
<img src="http://www.example.com/wp-content/uploads/2016/09/example.png" class="ls-bg" alt="alpha_video" style="padding: 0px; border-width: 0px; width: 0px; height: 0px; margin-left: 765.5px; margin-top: 299px;">
After the resize of the window the image size of that element suddenly changes (some kind of on the fly HTML manipulation)
<img src="http://www.example.com/wp-content/uploads/2016/09/example.png" class="ls-bg" alt="alpha_video" style="padding: 0px; border-width: 0px; width: 1508px; height: 612.625px; margin-left: 0px; margin-top: -11.8125px;">
How is such a resize being done?
Why doesn't it happen after the initial load?
How can I trigger it?
How can I trigger some kind of repaint after pageload that will unhide
those elements?
function afterload(callback) {
if (document.readyState === 'complete') {
callback();
} else {
jQuery(window).on('load', callback);
}
}
afterload(function () {
jQuery(window).trigger('resize');
});
In the past I've had luck with:
-webkit-transform: translate3d(0,0,0);
and/or in older IE:
hasLayout: true;
If you share some more info might be able to pinpoint it down a bit more.
With help of Michael Sparks I created this solution. It can be placed anywhere in the header, body or footer. It will be executed after the entire page has loaded to make sure that all elements get fixed.
<script type="text/javascript">
jQuery( window ).load(function(){
jQuery( window ).trigger( 'resize' );
});</script>

I want to load an overlay when the user closes the web browser

When a user presses the close button on the browser or tab, I want to action an overlay, wait for a second, then close. I know its not a done practice and I've stood on my soap box and cried about what is acceptable to the user and such but, they want it...
I know that the browsers close action is pretty explicit in what it can do, so where do I start?
Thanks
you could hook the onbeforeunload event, and have a overlay element hidden, then show it inside the event
overlay element
<div id="dark-overlay" style=""></div>
css
#dark-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
opacity: 0.6;
z-index: 1000;
display: none;
}
javascript
<script type="text/javascript">
window.onbeforeunload = function(event){
var overlayelement = document.getElementById('dark-overlay');
overlayelement.style.display = 'block';
return 'are you sure you want to quit?';
}
</script>
note this won't exactly achieve what you asked: it will show an overlay, along with a browser confirm dialog containing the text you returned.
I couldn't think of a way to wait a second before exiting, except putting a loop that exits after the defined amount of time which is terribly inefficient.
I know that the browsers close action is pretty explicit in what it can do
Correct.
It can pause while asking the user if they really want to close the window or not using a standard UI.
… and that's it.
so where do I start?
But telling your client that browsers don't provide any way to do what they want.

IE11 Input type Text content goes to new line

I am using simple text input (type=text) along with the angularJS in my project.
HTML Markup
<input type="text"
ng-model="startDate"
ng-class="{'fieldBorder' : dateRangeSelIndex == 0}"
ng-focus="setBorderOnFocuse($event,0)" />
I am using following JavaScript code to set the border of input when it get focus.
$scope.setBorderOnFocuse = function ($event, selIndex) {
$scope.dateRangeSelIndex = 0;
}
The behaviour works fine in Firefox and Chrome Browser but when I test it in IE11, The content of the input box goes to second line after the click-course position.
Check following screenshot of behaviour.
I already checked the CSS applied to it and the input box has enough length to handle the content in one line.
Thanks in Advance!
Edit
CSS Applied to the input
padding: 0;
width: 100px;
height: 27px;
font-size: 12px;
white-space: nowrap;
line-height: normal;
JS Fiddler for same http://jsfiddle.net/U3pVM/21997/
I cannot reproduce the same behaviour in jsfiddler but I found one interesting thing that this might be due to the cross added by IE11 in input text on focus.

window.alert() is not available in packaged apps

I am making a Chrome application. I keep getting the error in console:
window.alert() is not available in packaged apps. extensions::platformApp:17
Line 17 of that file is just a line of code to log the error to the console. Is there a way to alert the user of an event in a chrome app (like this image?)Is it because I have adblock installed in Firefox (I don't use Chrome)? I thought alert() was pretty basic. Thanks for any help.
The alert function has been disabled in Chrome packaged apps, because it halts the execution of Javascript and thus provides a poor user experience. For development purposes you should use console.log and for user facing interactions you should use a HTML based dialog.
You can make your own synchronous alert/prompt with a function that waits for a jQuery promise before completion and then when the user clicks the "OK" button resolves the promise. Then when ever you replace your "alert" with "myCustomAlert" you have to declare the function it's called in as an "async function" and then "await" before the call.
This may sound complicated but if you play with it in JSFiddle it's quite simple.
I found this useful if you are porting over an app where you can't break the function up into different sections very easily. This does requires the jQuery library.
Here is my example https://jsfiddle.net/littlej247/g4k2h56c/5/
//*****HTML*********
<button type="button" id="alertMe">Alert ME!</button>
<div id="backgroudDiv"> <!-- This is optional but I like to grey out the background -->
<div id="alertDiv">
<b><span id="alertTitle"></span></b>
<br />
<span id="alertText"></span>
<hr>
<button type="button" id="alertDone">OK</button>
</div>
</div>
//Remember JS can't run in HTML files on chrome apps so functions are called by DOM
document.getElementById("alertMe").onclick = async function () {
console.log("Starting function \n Processing a bunch of stuff, calculating variable(s)....");
await myCustomAlert("Alert Title Here","Message");
console.log("Continue processing stuff with the variable(s) after the alert is clicked.... \n function finished");
};
//*****JavaScript*********
//Alerts can not be used in chrome apps, myCustomAlert function is a replacement.
var alertPromise
function myCustomAlert(messageTitle,messageBody){
console.log("myCustomAlert has been called");
alertPromise = $.Deferred();
document.getElementById("alertTitle").textContent=messageTitle;
document.getElementById("alertText").textContent=messageBody;
document.getElementById('backgroudDiv').style.display='block';
return $.when(alertPromise).done();
}
document.getElementById("alertDone").onclick = function () {
console.log("Finally, User clicked Done, \n now we can get back to work..");
document.getElementById('backgroudDiv').style.display='none';
alertPromise.resolve();
return(false);
};
//*****Styles*********
#alertDiv {
width: 400px;
padding: 15px;
margin: 100px auto auto auto;
z-index: 10000;
background-color: lightblue;
border-style: solid;
border-color: black;
}
#backgroudDiv {
display: none;
position: fixed;
z-index: 9000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
}

Categories