Navigating to second div after page loads using javascript - javascript

I'm trying to use javascript to navigate to the second div after the page loads, but it's not working for some reason. What am I doing wrong?
<script type = "text/javascript">
window.location.hash = "second";
</script>
#first {
border: 1px solid red;
width: 100%;
height: 100%;
}
#second {
border: 1px solid blue;
width: 100%;
height: 100%;
}
<div id = 'first'> </div>
<div id = 'second'> </div>

Make sure your script runs after the document is loaded. Since you've tagged jQuery, this should work:
$(function() {
window.location.hash = "second";
});
Fiddle

Works for me! Be sure only that the javascript runs when the document is loaded, an easy way is to put it a the end of the document. If you want do it with jquery use on document ready.

Related

How to change all of a div's style attribute using JavaScript?

I'm working on my own in browser live HTML/CSS code editor. What I'm having trouble with is applying the css styles typed out by the user to my div preview pane.
What I currently have is
<html lang="en">
<head>
<meta charset="utf-8">
<title>Code Editor</title>
<style>
.wrapper{
width: 100%;
}
.textWrapper {
width: 30%;
height: 100%;
float: left;
}
#css{
height: 300px;
width: 100%;
}
#html {
height: 300px;
width: 100%;
}
#preview {
height:600px;
width: 400px;
float:left;
border:2px solid black;
margin: 20px;
}
</style>
</head>
<body>
<div class ="wrapper">
<div class ="textWrapper">
<textarea placeholder="CSS..." id="css"></textarea>
<textarea placeholder="HTML..." id="html"></textarea>
</div>
<div id="preview"></div>
<button onclick="launch()">Launch</button>
<button onclick="toggleCSS()">Toggle</button>
<button onclick="clear()">Clear</button>
<script src="bebk9hScripts.js"></script>
</div>
</body>
</html>
and for my script page
function launch() {
document.getElementById("preview").innerHTML = document.getElementById("html").value;
}
function toggleCSS() {
document.getElementById("preview").style = document.getElementById("css").value;
}
but that is not working. Any suggestions? Also I realize using an iframe would be easier but we aren't supposed to.
A simple and effective way to accomplish what you're trying to do is to set the innerHTML of your preview element. This does not prevent you from utilizing HTML, CSS, or JavaScript in any way, so long as all necessary dependencies have been accounted for prior to your preview element. The simple implementation is:
var preview = document.getElementById("preview");
var html = document.getElementById("html").value;
var css = document.getElementById("css").value;
preview.innerHTML = html;
preview.innerHTML += '<style>' + css + '</style>';
However, as a developer in a very rapid environment, I can honestly say, using an interval to refresh the preview is much appreciated when you're trying to quickly update things. It'll be up to you as to how fast of an interval you'll use to refresh, or you could give your users a setting for update intervals.
Keep in mind though, that using intervals can cause undesired behavior such as animations being cutoff, etc. This is why a lot of code editors online use a refresh or run button in the first place. But I'd like to point out the usefulness of utilizing the keyup event that is available to us.
Coupling the keyup event with a timer, a manual refresh button, and an interval would be my recommendation:
var html = document.getElementById("html");
var css = document.getElementById("css");
// Use the `keyup` event as a primary check for updates.
var keyDelay = 1000;
var keyRecieved = false;
var timeSinceLastKeyRecievedInMilliseconds = 0;
document.addEventListener('keyup', prepareForRefresh);
function prepareForRefresh() {
keyRecieved = true;
timeSinceLastKeyRecievedInMilliseconds = 0;
}
function update() {
var preview = document.getElementById("preview");
preview.innerHTML = html.value;
preview.innerHTML += '<style>' + css.value + '</style>';
}
// Use an interval for checking if we should update.
setInterval(function() {
if (keyRecieved) {
timeSinceLastKeyRecievedInMilliseconds += 100;
if (timeSinceLastKeyRecievedInMilliseconds >= keyDelay) {
timeSinceLastKeyRecievedInMilliseconds = 0;
keyRecieved = false;
update();
}
}
}, 100);
// Use a high interval as a fail-safe for flukes.
var interval = 180000;
setInterval(update, interval);
input[type=text] {
margin: 5px;
background-color: #fffa;
border: 2px solid transparent;
border-bottom: 2px solid #fff;
border-radius: 5px;
}
.update {
width: 20%;
padding: 10px;
margin: 5px;
background-color: #f33a;
cursor: pointer;
user-select: none;
}
.primary-content {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
html, body { overflow-y: auto; }
<link href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2940219/PerpetualJ.css" rel="stylesheet"/>
<div id="primary-content" class="primary-content">
<input id="html" type="text" placeholder="HTML" />
<input id="css" type="text" placeholder="CSS" />
<div class="update" onclick="update();">Refresh</div>
<div id="preview"></div>
<div id="refresh-preview"></div>
</div>
The simple example above utilizes a combination of the keyup event, a timer for detecting how long it's been since the user provided input, and a high interval as a fail-safe. This is close to the method utilized by CodePen, and I heavily recommend it for a web focused editor. Feel free to check out my implementation of this in it's simplest form over on CodePen.
Your Code works!
EDIT: Well, at least kind of. It applies the styles directly only to the preview element, not its children (see comments below this post).
Below ist my old answer:
There is nothing wrong with it, and the issue must be somewhere else.
Possible issues that come to mind are:
The CSS entered by the user is not valid, or is overwritten by another stylesheet
The Javascript function to update the file does not get triggered
The elements referenced in the Javascript are the wrong ones
Here is minimal working example using your code:
function toggleCSS() {
document.getElementById("preview").style = document.getElementById("css").value;
}
document.getElementById("apply_css").onclick = toggleCSS;
<textarea id="css" cols="40" rows="5">
width: 150px;
height: 100px;
border: 1px solid green;
background: rgb(170, 200, 250);
</textarea>
<br>
<button id="apply_css">Apply CSS!</button>
<br>
<div id="preview"></div>

How to apply a jQuery effect to an element before page is fully loaded?

I want to make custom height of an element using jQuery. height is being changed but an effect (like blink effect) is being shown on page load every time. How to solve this problem?
$(document).ready(function() {
$('.jQuery-Container').height('100px');
});
.jQuery-Container {
background-color: Red;
height: 700px;
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="jQuery-Container">
This is text..!!
</div>
On page load height of the div is being changed but after the page is fully loaded. I want to change height before the page is fully loaded.
You can See my jsfiddle here.
You could do like this, where you run a script immediately after the element, and as long as it is plain javascript, it will work.
.JS-Container {
background-color: Red;
height: 700px;
width: 200px;
}
<head>
<script>
function changeThis(sel) {
document.querySelector(sel).style.cssText = 'height: 100px;';
}
</script>
</head>
<body>
<div class="JS-Container">
This is a sample text
</div>
<script>changeThis('.JS-Container');</script> <!-- this will run before page is fully
loaded, so no "blink" will occur -->
</body>
make you div first hidden then after your jquery logic make div visible
CSS
.jQuery-Container {
background-color: Red;
height: 700px;
width: 200px;
display:none;
}
JS
$(document).ready(function(){
$('.jQuery-Container').height('100px').show();
});

Display loader on load event and remove the loader when background image is loaded

I have two divs.
1 : where background image is loaded
2 : where loader gif is loaded.
what I want is , when there is a window.load() event is called then loader gif should displayed , and when background image is fully loaded , then loader gif should be removed. that's what I want to achieve.
$(window).load(function (){
$('.background_image_div').load(function(){
$('.gif_loader_image').hide();
});
});
// this code is not working.
.background_image_div{
background: url(http://www.banneredge.com/images/portfolio.jpg);
width: 600px;
height: 300px;
margin: 0 auto;
border: thin black solid;
z-index: 900;
}
.gif_loader_image{
position: absolute;
width: 50px;
height: 50px;
background: url(https://media0.giphy.com/media/3oEjI6SIIHBdRxXI40/200_s.gif);
// border: thin red solid;
left: 55%;
bottom: 15%;
z-index: 1001;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gif_loader_image"></div>
<div class="background_image_div">
</div>
Thank you.
instead of $(window).load(function (){ do a $( document ).ready(function() { as,
$( document ).ready(function() {
// Handler for .ready() called.
$('.background_image_div').load(function(){
$('.gif_loader_image').hide();
});
});
EDIT Caveats of the load event when used with images as taken from here, .load API
EDIT 2 try a poller, keep polling and check for the image inside the div using .length > 0. Do some changes to your html,
Keep a div and then an image tag inside it with this structure, <div id="backgroundImageDiv"><img src="whatEverTheURLIs" id="backgroundImageID"></div>
Inside your poller check if $("#backgroundImageDiv > #backgroundImageID").length() > 0
If the condition satisfies, hide the gif loader using .hide(). Check for the syntaxes please.
By poller I mean an interval timer.
You can do as like this way.
Just see this link
<div class="feature"><div class="loader"><img src="http://www.ajaxload.info/cache/FF/FF/FF/00/00/00/1-0.gif"></div></div>
$(function(){
var bgimage = new Image();
bgimage.src="http://cdn.wonderfulengineering.com/wp-content/uploads/2016/01/nature-wallpapers-10.jpg";
$(bgimage).load(function(){
$(".feature").css("background-image","url("+$(this).attr("src")+")").fadeIn(2000);
$(".loader").hide();
});
});
http://jsfiddle.net/n4d9xxon
You can try like this :
$(document).ready(function (){
$('.gif_loader_image').fadeOut(1000);
});
body{
background: url(http://www.banneredge.com/images/portfolio.jpg);
width: 100%;
height: auto;
}
.gif_loader_image{
position: fixed;
width: 100%;
height: 100%;
left: 0px;
bottom: 0px;
z-index: 1001;
background:rgba(0,0,0,.8);
text-align:center;
}
.gif_loader_image img{
width:30px;
margin-top:40%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gif_loader_image">
<img src="https://media0.giphy.com/media/3oEjI6SIIHBdRxXI40/200_s.gif" alt="Loader..."/>
</div>
<div class="background_image_div"></div>
The main problem is that your $(window).load doesn't even fire
Why
This won't work since the .load() method was fully removed by jQuery 3 and since you are working with the version 3.1.1 it's not a surprise that your code doesn't work. You have to use now the .on() method to achieve the same effect
So
$(window).load(function (){
$('.background_image_div').load(function(){
$('.gif_loader_image').hide();
});
});
would turn into
$(window).on('load', function (){
$('.background_image_div').on('load', function(){
$('.gif_loader_image').hide();
});
});
Notice
Since you have already the $(window).load function at the beginning you don't have to define it again for your background image because this method will only be fired when all images are fully loaded so I think in your case this should also do the job.
jQuery
$(window).on('load', function () {
$('.gif_loader_image').hide();
});

Jquery on button click do timer with progress-bar

So I was trying to make a little game but the first step just doesn't work.
This is my code
<div id="box1">
<button id="button">Click Me</button>
<div id="progress-bar"></div>
</div>
$('button').click(function() {
var progressBar = $('#progress-bar'),
width = 0;
progressBar.width(width);
var interval = setInterval(function () {
width += 2.5;
progressBar.css('width', width + '%');
if (width >= 100) {
clearInterval(interval);
}
}, 125)
});
#progress-bar {
width: 0;
background: red;
text-align: center;
overflow: hidden;
height: 4px;
position: absolute;
bottom: 0px;
}
#box1 {
height: 100px;
width: 600px;
position: relative;
border: 1px solid grey;
}
So when clicking the button there will be a progress-bar at the bottom of box1.
When doing a document ready it works but when using the .click it doesn't work.
When doing a document ready it works but when using the .click it doesn't work.
It works when you have a $(document).ready wrapped around your code because that instructs the javascript engine to wait until all js is fully loaded before trying to execute.
If you don't have the $(document).ready and you click before the everything is loaded, then you'll get a console error.
Press F12 to open developer toos and perform the same action, I would suspect you'll see an error in the console.

How can I log information without using alert in userscripts

i have an userscript which traces all the dynamically created tags in javascript of a webpage. the problem here is presently i am using alert box to dispaly the output. The problem with alert() is that it can be very obtrusive. For every alert, you need to click the OK button to proceed which wastes your time. so i want an alternative method like log files other than alert box. how can i do this.
i am restricted to use console.log
I would use some kind of console element statically placed on your page which can be hidden if necessary. See this jsFiddle.
HTML:
<div id="console">
<div class="header">
Console
<span class="expand" onclick="toggleConsole();">+</span>
</div>
<div class="content" style="display: none;"></div>
</div>
CSS:
#console {
position: fixed;
right: 0px;
bottom: 0px;
width: 300px;
border: solid 1px #dddddd;
}
#console .header {
background-color: #ededed;
border: solid 1px #dddddd;
}
#console .header .expand {
padding-right: 5px;
float: right;
cursor: pointer;
}
#console .content {
overflow: auto;
background-color: #F9F9F0;
width: 100%;
height: 180px;
}
Javascript:
function log(text) {
var consoleContent = document.getElementById('console')
.getElementsByClassName('content')[0];
var line = document.createElement('div');
line.className = 'consoleLine';
line.innerHTML = text;
consoleContent.appendChild(line);
}
function toggleConsole() {
var content = document.getElementById('console')
.getElementsByClassName('content')[0];
if (content.style.display === "none") {
content.style.display = "block";
document.getElementById('console')
.getElementsByClassName('expand')[0].innerHTML = "-";
} else {
content.style.display = "none";
document.getElementById('console')
.getElementsByClassName('expand')[0].innerHTML = "+";
}
}
document.onload = function() {
document.getElementById('console')
.getElementsByClassName('expand')[0].onclick = toggleConsole;
};
Use log("some text"); to output to your console !
Install firefox add-on to your Mozilla(if you are using) and you the follwing code:
console.log("test"+your_variable);
So above code will display all logs in console.If IE press F12 and check console.
If a normal user should be able to see it, using the console is not a very user-friendly way.
Define a space on your webpage (a <div> might be handy) where you want the information to be, and just add the messages to that space using javascript (or jQuery) to modify the DOM:
HTML:
<div id='logmessages'>Log messages:</div>
JavaScript
function log(yourMsg) {
document.getElementByID('logmessages').innerHTML() += yourMsg;
}
It might be friendly to allow the user to show/hide the div with a button or another way.
Create a fixed div either at the top, bottom or corner of your page with set width/height and overflow auto, then insert the log entries in it.

Categories

Resources