Fade in / Out div with Javascript - javascript

So I have some javascript for a website but at the moment the only way I can get it to work is if it is mixed in with the HTML. I've read this is bad practice, but I can't figure out how to get it to work as a script in the head section. Can anyone help me out? I have read tonnes of similar questions on here but can't get it to work.
Thank you,
Alex
Here's the code I have:
<li>About</li>
I'm then fading it out again by adding:
and having a div that spans the width and height of the page so the user can click anywhere, not sure if this is a good way and is alright to use.
Thanks

I think you just forget to use the document ready.
The code you need:
<head>
<script type="text/javascript">
$(document).ready(function(){
$('.about_button').click(function(){ $('.about_background, .about_close').fadeIn('fast'); });
$('.about_close').click(function(){ $('.about_background').fadeOut('fast'); });
});
</script>
</head>

In your html you can place the elements:
<li>About</li>
and then at the bottom of the body put a reference to a js file (it should be at the bottom of the file rather than in the head so that the html loads first and the elements are ready when you use js to bind event handlers to them)
<script src="<file path>"></script>
In an external js file you can bind the event handler to them:
$(".about_button").click(function(){
$('.about_background, .about_close').fadeIn('fast')
}
$(".about_close").click(function(){
$('.about_background').fadeOut('fast')
}

Use jquery selectors to target your HTML elements and put listeners on them:
$('.about_button').on('click', function() {
$('.about_background, .about_close').fadeIn('fast')
})
$('.about_button') is the selector you use to target the element.
on('click' sets an onclick listener on the targeted element
function() { ... } is the callback function that'll get called when the listener gets triggered

Use
<script src="path/to/file.js"></script>
In HTML 5 you dont need to specify the type, else you need to specify type="text/javascript"

Related

Rerun Jquery function onclick

I have a simple jquery script that changes the url path of the images. The only problem is the doesn't apply after I click the load more button. So I'm trying to do a workaround where it calls the script again after clicking the button.
<script type='text/javascript'>
$(document).ready(function ReplaceImage() {
$(".galleryItem img").each(function() {
$(this).attr("src", function(a, b) {
return b.replace("s72-c", "s300")
})
})
});
</script>
HTML
Load More
While Keith's answer will get you what you are looking for, I really can't recommend that approach. You are much better off with something like this.
<script type="text/javascript">
$(function() {
var replaceImage = function() {
$('.galleryItem img').each(function() {
$(this).attr('src', function(index, value) {
return value.replace('s72-c', 's300');
});
});
};
replaceImage();
$('.js-replace-image').on('click', replaceImage);
});
</script>
Using this html
<button class="js-replace-image">Load More</button>
By taking this approach, you do not expose any global variables onto the window object, which can be a point of issue if you work with other libraries (or developers) that don't manage their globals well.
Also, by moving to a class name and binding an event handler to the DOM node via JavaScript, you future proof yourself much more. Also allows yourself to easily add this functionality to more buttons very easily but just adding a class to it.
I updated the anchor tag to a button because of the semantics of what you need to do - it doesn't link out anywhere, it's just dynamic functionality on the page. This is what buttons are best served for.
I'd also recommend putting this in the footer of your site, because then, depending on your situation, you will already have the images updated properly without having to click the button. The only need for the button would be if you are dynamically inserting more images on the page after load, or if this script was in the head of your document (meaning jQuery couldn't know about the images yet).
I hope this helps, reach out if you have questions.

jquery not quick enough to take effect

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.

Can someone explain to me how this is possible? (Picture in comments)

So I'm trying to link up my html and javascript files in notepad++, but it isn't working properly.
I wanted to know how it is possible that it writes test, but doesn't remove the div. Can anyone explain this? Thanks in advance!
1, jQuery isn't linked. Meaning, you don't have <script type='text/javascript' src='myjQueryfile.js'></script> in your HTML, you'll want to put it before your script.
2:
Because the element with the ID of blue, doesn't exist yet. The DOM - basically the object of your HTML - has yet to be constructed when your script is run, which in this case is the top of the page, before blue comes into existence. You'll want to use an event to fix this, typically $(function(){ ... }); which will execute your code when the DOM is ready.
Also, document.write just writes code then and there, meaning exactly where the document.write calls is made, the HTML will be outputted.
You should have linked jquery. You're trying to use it without having it linked.
The script is loaded in the head. At the time the script executes the body of the document is not built, so nothing is removed. If you were to use the document.ready callback (and had properly included jQuery) it would work
$(function(){ $("#blue").remove(); });
A plain js version of this is
window.onload = function(){
var b = document.getElementById("blue");
b.parentNode.remove(b);
};
At the time the script runs, only the portion of the document up to the <script> tag has been loaded. You need to delay until the DOM has fully loaded before the script can target the DOM:
document.addEventListener("DOMContentLoaded", function(event) {
$("#blue").remove();
});

Uncaught TypeError: Object [object Object] has no method 'overlay'

Why do I get this error from my overlay jquery code?
This is the code:
jQuery(document).ready(function($) {
// if the function argument is given to overlay,
// it is assumed to be the onBeforeLoad event listener
$("a[rel]").overlay({
mask: 'darkred',
effect: 'apple',
onBeforeLoad: function() {
// grab wrapper element inside content
var wrap = this.getOverlay().find(".contentWrap");
// load the page specified in the trigger
wrap.load(this.getTrigger().attr("href"));
}
});
});
This code is the overlay like this: http://flowplayer.org/tools/demos/overlay/external.html
Halp?
ps. Sorry for my bad english.
"Could not find Overlay: nofollow" is caused by using a non-specific css selector to find the links you want to attach your overlay to.
Including the javascript properly was the correct answer to the initial question... I came to this page based on the Overlay: nofollow issue in a comment.... since this is the first thing I found and didn't find an answer I wanted to comment here since I found it is caused by the css selector finding other uses of .. and there isn't a nofollow overlay...
assuming 'overlay' is the id of your div as in the following:
<!-- overlayed element -->
<div class="apple_overlay" id="overlay">
< !-- the external content is loaded inside this tag -- >
<div class="contentWrap"></div>
</div>
you should be doing something like:
$("a[rel=#overlay]").overlay(
instead of:
$("a[rel]").overlay(
You need to load the overlay plugin before jQuery will see it as part of the object; see below.
Note: the plugin must come after the jQuery script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://cdn.jquerytools.org/1.2.6/all/jquery.tools.min.js"></script>
Got the same problem and found a really strange solution.
I just included jquery.tools before jquery.ui in this way:
<script src='js/jquery-1.4.2.min.js' type='text/javascript'></script>
<script src='js/jquery.tools.min.js' type='text/javascript'></script>
<script src='js/jquery-ui-1.7.2.custom.min.js' type='text/javascript'></script>
That's all. No idea why it works now but it does the job.
Did you include the overlay script src in your page?

call function to highlight code

Please see the the following http://valogiannis.com/recent/ .I have a webpage and when user click XHTML code a div with id result loads the contents of a webpage (in this case codes/advocasys.html). In fact what I wish to do is to highlight the html code. I have link the necessary css/js. I use the SyntaxHighlighter 3.0.83. This highlighter needs to call the SyntaxHighlighter.all() after the <pre> tag (more info here). If I have the html code in the same page which I want to highlight works nice, but I cannot make it to work, when the script loads the external page advocasys.html. I tried to put the
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
in the bottom of the advocasys.html, but It didn't work. How can I make it work?
Thanks in advance.
The .all() call attaches an event handler to window.load which already happened, instead use .highlight(), like this:
SyntaxHighlighter.highlight();
You need to call SyntaxHiglighter in the callback function after the data is returned:
$('#myLink').click(function(){
$('#result').load('codes/advocasys.html', function() {
$('#result').show();
$('.scroll-pane').jScrollPane();
SyntaxHighlighter.highlight();
});
return false;
});

Categories