javascript add additional attribute change - javascript

I Have this Javascript:
<script>
$('.tile').on('click', function () {
$(".tile").addClass("flipOutX");
setTimeout(function(){
$(".tile-group.main").css({ marginLeft:"-40px", width: "1080px"}).load("company-overview.html");
}, 2000);
});
</script>
This is great as it loads another page into the current page and that is helpful.
Question is, how can I change the background color of the a class that is already loaded?
The class is called metro as defined in its css that is included and is used to apply the background color of the main page.
EDIT -------
My JS now looks like this and still doesn't work...
<script>
$('.tile').on('click', function () {
$(".tile").addClass("flipOutX");
setTimeout(function(){
$(".metro.tile-area-darkCrimson").css('background-color', '#f36c20');
$(".tile-group.main").css({ marginLeft:"-40px", width: "1080px"}).load("musability-musictherapy-company-overview.html");
}, 2000);
});
</script>
not sure what is wrong any help really appreciated here !
btw the CSS class for .metro.tile-area-darkCrimson looks like this .....
.metro .tile-area-darkCrimson {
min-width: 100%;
height: 100%;
background-color: #1f255b !important;
transition: background-color .25s ease-in-out;
-moz-transition: background-color .25s ease-in-out;
-webkit-transition: background-color .25s ease-in-out;
}

Maybe you should only load a fragment of the company-overview.html page rather then adding another body element.
From https://api.jquery.com/load/
Loading Page Fragments
The .load() method, unlike $.get(), allows us to specify a portion of
the remote document to be inserted. This is achieved with a special
syntax for the url parameter. If one or more space characters are
included in the string, the portion of the string following the first
space is assumed to be a jQuery selector that determines the content
to be loaded.
$( "#result" ).load( "ajax/test.html #container" );
After the content was load you might also add/remove css classes or alter the css by passing a callback function:
Callback Function
If a "complete" callback is provided, it is executed after
post-processing and HTML insertion has been performed. The callback is
fired once for each element in the jQuery collection, and this is set
to each DOM element in turn.
$( "#result" ).load( "ajax/test.html", function() {
$('.my-class', '#result').removeClass('my-class');
});

you can add a callback to your load method:
$(".tile-group.main").css({ marginLeft:"-40px", width: "1080px"}).load(
"company-overview.html",
function() {
$(".metro").css("background-color", "red");
}
);

Related

jQuery .fadeOut method on and element that is being appended after DOM load

(I am 9 weeks into a boot camp, so I apologize for the potentially rudimentary nature of this...)
I am appending an element to the DOM (a button) within a conditional:
$('.buttonsAndInputs').append(`<button id="clearHistoryButton">Clear All</button>`);
When this button is clicked, it runs through a series of functions to empty an array and clear some other content off the DOM. I would like to use the .fadeOut method of jQuery to remove THE BUTTON.
I have this in a subsequent function:
$('#clearHistoryButton').remove();
I would like to:
$('#clearHistoryButton').fadeOut(1000);
...so that it disappears in a fancy fashion.
It's not working - it simply waits one second and then - POOF - is gone.
This is my first question. This community has been ESSENTIAL in my growth in this realm and, as always, I appreciate all of you so very much.
Did you try transition: opacity 1s in your CSS ?
Advantage:
Hardware accelerated (GPU), i.e. it doesn't bother your main processor (CPU) with this task, whereas jQuery's fadeOut() function is software based and does take CPU resources for that effect.
Steps:
Add transition: opacity 1s to your CSS rules of the desired button element
here: ( #clearHistoryButton )
Add a CSS rule with button.fadeMeOut with opacity: 0
Add a simple jQuery function to add the class ".fadeMeOut" at click
Then remove button with setTimeout(function(){$('#clearHistoryButton').remove()},1000)
Run code snippet
$(function() { // Shorthand for $( document ).ready()
$("#clearHistoryButton").on( "click", function() {
// first: fade out the button with CSS
$(this).addClass("fadeMeOut");
// then: after fadeOut effect is complete, remove button from your DOM
setTimeout(function(){
$('#clearHistoryButton').remove();
},1000);
});
});
button {
opacity: 1;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
transition: opacity 1s;
}
button.fadeMeOut {
opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="clearHistoryButton">Press to hide me</button>

How to load a Javascript function before the HTML markup ?

I have a Javascript script that is sort of heavy to load and I noticed that on slower configurations, the script does load after the html markup, and that make my page to not work properly.
Loading the javascript first and then the html markup fixes my issue.
I found simple way to do it with the following :
Javascript :
jQuery(document).ready(function ($) {
$(window).load(function () {
setTimeout(function(){
$('#preloader').fadeOut('slow', function () {
});
},2000);
});
});
html :
<div id="preloader"></div>
<p>EXEMPLE</p>
and finally css :
#preloader {
position: fixed;
left: 0;
top: 0;
z-index: 999;
width: 100%;
height: 100%;
overflow: visible;
background: #333 url('//cdnjs.cloudflare.com/ajax/libs/file-uploader/3.7.0/processing.gif') no-repeat center center;
}
http://jsfiddle.net/harshdand/593Lqqnm/2/
It is jQuery though. I would like to do the same in vanilla JS since I am not proficient with jQuery and for performance reasons.
Any way someone can show me the vanilla JS equivalent of the script or a better way ?
The (document).ready you use is triggered once the DOM is fully loaded.
In your case, as you mentioned, this means that your JS is also loaded.
So basically you're looking at the DOM to see if JS is loaded. I think a nicer solution would be to look at the JS directly an determine from that is you can remove the preloader.
But to answer your question, the vanilla equivalent could be something like this:
According to youmightnotneedjquery.com you could replace the (document).ready part with this:
function ready(fn) {
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
You could than use this to trigger a CSS change in opacity, and remove the element completely once the opacity animation is done.
var target = document.getElementById('preloader');
target.style.opacity = '0';
setTimeout(function(){target.parentNode.removeChild(target);}, 1000);
In order to make the opacity fade nicely you need to add a transition to the preloader in CSS:
-webkit-transition: opacity 1000ms linear;
transition: opacity 1000ms linear;
Just make sure the animation in the CSS is the same duration as the timeout in the JS.
The complete code would be something like this: http://jsfiddle.net/8ua69dbL/10/

Browser caching image prevents fade in

I have a page where I want all my images to fade in once they have loaded, but separately, and I have it working fine using the following...
<style>
img.imgfade {display:none;}
</style>
<script>
$(document).ready(function() {
$('img.imgfade').load(function() {
$(this).fadeIn('slow');
});
});
</script>
The problem I have here, is after navigating away from the page, and then coming back again, the images are no longer there. This is probably because they are already stored in the browser cache, and so are already loaded before my javascript runs.
I've been researching this all afternoon, but can't find an alternative where the images load and fade in seperately. One method I found says to include an .each() function to the .load(). This each can check if an image is already complete and if so just manually call .load() but when I add it, the images don't even load the first time round.
<script>
$(document).ready(function() {
$('img.imgfade').load(function() {
$(this).fadeIn('slow');
});.each(function() {
if(this.complete) {
jQuery(this).load();
}
});
</script>
SOLVED: The question was solved below, so I am sharing my full code incase it helps anyone else. This will fade in your images one at a time as they load, and also will not be affected by the browser caching images when you return to the page.
<style>
img.imgfade {display:none;}
</style>
<script>
(function ($) {
$(document).ready(function() {
$('img.imgfade').load(function() {
$(this).fadeIn('slow');
})
.each(function() {
if(this.complete) {
jQuery(this).load();
}
});
})(jQuery);
</script>
});.each(function() {
try to remove the semicolon ; otherwise your code will raise a syntax error.
Remember to also add a }); for your each(function()... )
So the code becomes
...
})
.each(function() {
if(this.complete) {
jQuery(this).load();
}
});
You can make this happen with modern CSS3 transitions and a onload attribute like so:
<img src="http://www.hdwallpapersfan.com/wp-content/uploads/2013/10/mountain-4.jpg" onload="this.classList.add('show')">
img {
opacity: 0;
-webkit-transition: 1000ms opacity;
-moz-transition: 1000ms opacity;
-ms-transition: 1000ms opacity;
-0-transition: 1000ms opacity;
transition: 1000ms opacity;
}
img.show {
opacity: 1
}
Example
Granted, I used vanilla JS with this.classList which may not be suitable for you if you need older browser support
But you can always swap out for jQuery: $(this).addClass('show')
And here's an example using jQuery to perform the fade in:
<img src="http://www.hdwallpapersfan.com/wp-content/uploads/2013/10/mountain-4.jpg" onload="$(this).fadeIn(1000)">
img {
display: none;
}
Example

jquery div movement using css with panel changes

quite a large question here. Basically im making a site that has a central heading when you load the index.html but i want to use jquery to modify the header to move it to the top of the page in a transition when the user clicks a link, in addition i want the content to fade once the header has risen. So altering the panels by changing display: hidden;
If someone could offer a solution it would be greatly appreciated [im fairly new to js and havent done jquery before but it seems like jquery is the best library to use]
<!DOCTYPE html>
<html>
<head>
<title>Chris Calcroft • Arbitrator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/stuff.js"></script>
</head>
<body>
<div class='header'>
<img src='img/header.jpg' alt='header'>
<ul class='headerNav'>
<li id='about' onclick='pageChange(id);'>about</li>
<li id='projects' onclick='pageChange(id);'>projects</li>
<li id='contact' onclick='pageChange(id);'>contact</li>
</ul>
<div>
</body>
</html>
JS:
$(function pageChanger(id) {
$("id").click(function() {
$(".header").toggleClass(".header-transition");
});
});
CSS:
#font-face {
font-family: avant;
src: url('font/avant.ttf');
}
html {
background-color: black;
color: white;
font-family: avant;
}
.header {
position: fixed;
top: 50%;
left: 50%;
margin-top: -175px;
margin-left: -450px;
-webkit-transition: top 2s ease,
left 2s ease,
margin-left 2s ease,
margin-top 2s ease,
position 2s ease;
}
.header-transition {
top: 0;
left: 0;
margin-top: 0;
margin-left: auto;
margin-right: auto;
position: static;
display: block;
}
li {
text-decoration: none;
display: inline;
padding: .2% 1.3%;
}
li:hover {
color: gray;
}
This is what I have so far. I hit a wall when trying to pass the correct id to the jquery for it to toggle the class.
Thanks guys :)
$("id") means all elements that their tag names are id
you must use id in the function as below but however I don't think this is what you want.
$(function pageChanger(id) {
$("#"+id).click(function() {
$(".header").toggleClass(".header-transition");
});
});
if I have understood your case you should do:
$('.headerNav li').click(function(){
$(".header").toggleClass(".header-transition");
});
for more about selectors visit jquery selectors
Edit:
If each li will do something different then you should either give them ids and do:
$('#about').click( function(){
......
});
$('#project').click( function(){
......
});
$('#contact').click( function(){
......
});
and do this for all others. or:
$('.headerNav li').click(function(){
switch($(this).attr('id')){
case 'about':
//do something
case 'project':
//do something else
case 'contact':
//do another thing
}
});
A few things are wrong at first glance:
You are binding your click event twice - both via inline HTML onclick handler, and via jQuery click() method in your script.
The function you are binding in your onclick events has a different name to the one you're defining in your script, so nothing will be called when the event fires.
You're defining a named function inside your closure e.g. $(function pageChanger(id)...
This doesn't look right to me but I might be wrong on this.
The way you're passing your id to the function on each click event is wrong.
In your onclick statements you're passing 'id' to the function, which I assume you mean to be the value of the element's ID attribute, but this will not work.
On the other hand, in your script, you define your function's parameter as 'id', but then refer to it inside the function as a string in quotes i.e. "id". Because of this, your jQuery selector object $("id").click, in this form, is telling jQuery to select an 'id' element, which is invalid (there is no 'id' element in HTML).
Maybe a little off-topic here but I hope the above can help to improve your general knowledge of JS / jQuery.
What you can do is stick with the click() method in your script but, rather than use it in a function, you can simply bind it to your list elements directly.
Note: you might be better to put anchor elements inside your list elements and attach the click event to those as this is semantically better markup, and should avoid failed event firing in legacy browsers (I think IE7 doesn't listen to click events that aren't bound to anchor elements).
Try the following:
Change links to -
<li>Link text</li>
Change JS to this -
$(function(){
$(".headerNav a").click(function(e){
var elem = $(e.target), // e.target points to the element that triggered the event
elemId = elem.attr("id");
// it isn't clear what each unique element's click event will do, but here is where you defien that logic
})
})
Using e.target in a jQuery object is a much cleaner and more efficient way to dynamically bind an event to multiple elements.
I hope you find some / any of this useful.
The following code will toggle the header css on every list item click.
$(document).ready(function(){
var currentCssClass = $(".header").attr("class");
$(".header > ul > li").click(function(){
$(".header").toggleClass("header-transition");
});
});
Demo

Slow transition to hover state with Javascript

I am working on css in which when mouse hovers on images, it gets bigger. e.g.
#image-div img { width:100px; height:100px;}
#image-div:hover img { width:200px; height:200px;}
Now i want it to be animated a little. Like it shall zoom in slowly, and on mouse out, it shall zoom out slowly. Please help.
Note: I am not very well familiar with javascript.
These animations are typically done with Javascript. Rather than writing the Javascript by hand, it is probably easier to use the jQuery library, which includes the ".animate()" method. The animate method requires you give the destination css properties as parameters, like so:
(Since you wrote you are not familiar with Javascript, I've included everything you need to include the jQuery library)
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">google.load("jquery", "1.6.4");</script>
<script type="text/javascript">
$(document).ready(function(){
$("#image-div img").live({mouseenter:myfin,
mouseleave:myfout});
});
function myfin () {
$(this).animate({height: 200, width: 200},1000); //1000 = 1 second animation
}
function myfout () {
$(this).animate({height: '', width: ''},1000); //1000 = 1 second animation
//setting the height and width to '' will clear the inserted style, leaving you with your original style
}
</script>
Then all you should need is to set the height and width to 100px in your CSS, and remove the #image-div:hover definition.
If you would like to animate using class definitions in your CSS file, you can do so using a jQuery plug-in. See the following question for help on that:
jQuery.animate() with css class only, without explicit styles
If you don't need to support older browsers you could use the CSS3 transition attribute. It does not require any javascript and works on Safari, Firefox, and Opera. http://www.w3schools.com/css3/css3_transitions.asp
#image-div img {
width:100px;
height:100px;
transition:all 1s ease-in-out
-moz-transition:all 1s ease-in-out;
-webkit-transition:all 1s ease-in-out;
-o-transition:all 1s ease-in-out;
}
#image-div:hover img {
width:200px;
height:200px;
}
Look into the .animate() method and pair it with .hover(). This will allow you to apply a specific transition when the mouse is hovered over a specific element, in this case zoom, as desired.

Categories