jQuery very simple code seems to not work - javascript

Here is my jQuery code:
(function() {
var overlay = {
init: function() {
$('<div></div>', {
class: 'overlay'
})
.insertAfter('button');
}
};
overlay.init();
})();
I would expect this to put a div under my button however the HTML that is created contains no div:
<body>
<button>Reveal More Info</button>
</body>
Sorry if this is a newbie question, I have just started learning.
The HTML Head:
<head>
<title>jQuery rules</title>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="script.js"></script>
<style>
body {
background: yellow;
}
button {
margin: 100px 0 0 200px;
}
div {
display: none;
width: 600px;
height: 400px;
background-color: white;
border-radius: 40px;
position: absolute;
left: 25%;
top: 30%;
}
</style>
</head>

From jQuery documentation, see e.g., http://api.jquery.com/jQuery/#jQuery-html-attributes:
Blockquote
The name "class" must be quoted in the object since it is a JavaScript reserved word, and "className" cannot be used since it refers to the DOM property, not the attribute.

The problem is you are including the script.js in your header which is executing before the button is added to the dom so the insertAfter() will not be able to find the button to insert the div.
The solution here is to use document ready handler, or to insert the script at the bottom of the body(just before </body>)
//dom ready handler
jQuery(function ($) {
var overlay = {
init: function () {
$('<div></div>', {
'class': 'overlay'
}).insertAfter('button');
}
};
overlay.init();
});
Demo: Fiddle

Related

Inverting button action on click

I'm working with WordPress site where I want to show elements on button click.
I found this script, but it works the opposite how I want - it hides, instead of shows content. How can I invert it?
I want it to be hidden when pages loads and appear when clicked on button
Preview: https://www.w3schools.com/code/tryit.asp?filename=GGXM3P219FCN
$(document).ready(function () {
var togBtn = $('.tog');
var allergerns = $('.allergerns');
togBtn.one('click', hideAllergerns);
function hideAllergerns() {
allergerns.fadeOut();
togBtn.one('click', showAllergerns);
}
function showAllergerns() {
allergerns.fadeIn();
togBtn.one('click', hideAllergerns);
}
});
.allergerns {
width: 100px;
height: 100px;
background-color: #4aa3df
}
.tog {
width: 60px;
height: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<button class="tog">toggle</button>
<div class="allergerns"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Set the initial CSS styles.
Use JavaScript to toggle a specific class that shows your elements:
References should be stored inside a data-* Attribute, not by copy pasting code in case you need multiple toggling buttons or pane elements
Animations should be done using CSS, not jQuery. Preferably use GPU accelerable CSS properties like opacity, transform etc.
Finally, use jQuery's .toggleClass() to trigger a desired style-state
jQuery(function ($) { // DOM ready and $ alias in scope
$("[data-toggle]").on("click", function() {
$(this.dataset.toggle).toggleClass("is-active");
});
});
.pane {
overflow: auto;
background-color: #4aa3df;
width: 100px;
height: 100px;
transition: 0.3s;
max-height: 0;
opacity: 0;
}
.pane.is-active {
max-height: initial;
opacity: 1;
}
<button class="tog" data-toggle="#pane-1">Toggle 1</button>
<div id="pane-1" class="pane">Pane 1</div>
<button class="tog" data-toggle="#pane-2">Toggle 2</button>
<div id="pane-2" class="pane">Pane 2</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Why does draggable not work for dynamically created elements?

My draggable elements are created dynamically. every time I add an item, I call draggable() again. They get draggable classes, but don't drag.
When writing draggable to the debug console, it successfully works with non-dynamic elements.
$(window).on('load', function () {
var item = '<div class="item"></div>';
$field.append(item);
dragItems();
});
function dragItems() {
var $items = $('.item');
$items.draggable();
}
In the inspector, I see that the drag classes are created, but the movement does not occur.
Consider the following example.
$(function() {
function dragItems(dObj) {
dObj.draggable({
containment: "parent"
});
}
var item = '<div class="item"></div>';
$("#field").append(item);
dragItems($("#field .item"));
});
#field {
width: 400px;
height: 200px;
background: #CFC;
}
.item {
width: 100px;
height: 100px;
background: #CCC;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="field"></div>
I suspect there is more code to your example. This is wrapped in $(function(){}); which will wait until the document is ready. Similar to $(window).on('load').
The function is setup to accept a jQuery Object and assign Draggable to the Object. So you have to pass it the $("#field .item") object.
Now if you had created the object first, could be a little less code. Your current code is not creating an object but injecting HTML string by append. Consider the following.
$(function() {
function dragItems() {
$("#field .item").draggable({
containment: "parent"
});
}
var item = $("<div>", {
class: "item"
});
$("#field").append(item);
dragItems();
});
#field {
width: 400px;
height: 200px;
background: #CFC;
}
.item {
width: 100px;
height: 100px;
background: #CCC;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="field"></div>
This, I think, is more like what you want to do, where you just make all .item elements draggable. You can use either method. I would just make sure you create an Object one way or another to use with Dragable.
Hope that helps.

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 show not working with effects

I'm trying to show a fixed div using the show function of jquery. The show function works, but not when I try to add an effect with jquery ui. I have both jquery and jquery ui linked in an external file via a php include. When I use the inspector in chrome, I can see the blue box of the div I'm trying to show when I click the show button, yet the page remains unchanged.
This is my html:
<link rel="stylesheet" href="js/jquery-ui.min.css">
<script src='js/jquery-2.1.1.min.js'></script>
<script src="js/jquery-ui.min.js"></script>
<div class="twitterbar" id="baremily">
<a class="twitter-timeline" href="https://twitter.com/EmilyPalmaers" data-widget-id="number">Tweets by #EmilyPalmaers</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div>
<div class="twitterbar" id="barcharlotte">
<a class="twitter-timeline" href="https://twitter.com/CPalmaers" data-widget-id="number">Tweets by #CPalmaers</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div>
This is my jquery:
<script>
$(document).ready(function()
{
$("#twitteremily").click(function(e)
{
e.preventDefault();
if( $('#baremily').is(':visible') ) {
// it's visible, do something
$('#baremily').hide("blind");
}
else {
// it's not visible so do something else
if ($('#barcharlotte').is(':visible'))
$('#barcharlotte').hide("blind");
$('#baremily').show("blind");
}
});
$("#twittercharlotte").click(function(e)
{
e.preventDefault();
if( $('#barcharlotte').is(':visible') ) {
// it's visible, do something
$('#barcharlotte').hide("blind");
}
else {
// it's not visible so do something else
if ($('#baremily').is(':visible'))
$('#baremily').hide("blind");
$('#barcharlotte').show("blind");
}
});
}
);
</script>
and this is the css (note, the div I'm trying to show has a class and ID tag:
.twitterbar
{
position: fixed;
display: none;
top: 35%;
left: 50%;
margin-top: -10em;
margin-left: -10em;
z-index: 99999;
height: 20em;
width: 20em;
}
#media (min-width:961px) {
.twitterbar
{
top:50%;
margin-top: -16rem;
margin-left: -16rem;
height: 32rem;
width: 32rem;
}
}
I'm pretty much clueless at the moment, thanks in advance
http://jsfiddle.net/a9dbeo1o/
Recheck your script references.
To make sure jQuery is ready, try:
if ( jQuery.isReady ) {
alert('jQuery is ready');
}
Edit:
Just a note: I also see you have your jquery css file inside your js folder.
Edit 2:
Updated fiddle:
http://jsfiddle.net/a9dbeo1o/2/

JavaScript not working on page load

I was working with an html page now i am trying to rewrite a div style to another style it'll look like this <div class="fs-stretcher" style="width: 1170px; height: 480px;"></div>. for that i am using java script like this
<script>
window.onload=document.getElementsByClassName('fs-stretcher')[0].setAttribute("style","width: 0px; height: 0px; background-color: yellow;")
</script>
but it is not working somebody please help me to fix this.
You have to assign a function reference to window.onload.
window.onload = function () {
document.getElementsByClassName('fs-stretcher')[0].setAttribute("style", "width: 0px; height: 0px; background-color: yellow;")
};
your code is executing the statement document.getElementsByClassName.... and assigns the value returned by setAttribute to onload
Another way to place the script after you div.
<html>
<head>
</head>
<body>
<div class="fs-stretcher" style="width: 1170px; height: 480px;">adv</div>
<script>
window.onload = document.getElementsByClassName('fs-stretcher')[0].setAttribute("style", "width: 100px; height: 100px; background-color: yellow;")
</script>
</body>
</html>
This will also work fine. But if you use window.onload =function(){-----} is best way as answer above by Arun P johny.
window onload is a function, and you should need to bind a function to this event.
so try:
window.onload = function () {
document.getElementsByClassName('fs-stretcher')[0].setAttribute("style", "width: 0px; height: 0px; background-color: yellow;")
};
or you can create a function
function setElementOnLoad() {
document.getElementsByClassName('fs-stretcher')[0].setAttribute("style", "width: 0px; height: 0px; background-color: yellow;")
};
and bind it to onload of body tag:
<body onload="setElementOnLoad()">

Categories

Resources