jquery setting background image on load not working - javascript

currently im having a decent bit of trouble getting my jquery code to work. I'm trying to make the div load in with the correct background image but it doesnt wanna do so. I cant find out what might be wrong since im pretty new to jquery. I have a container set which needs a background image within the html attr 'srcpost' which contains something like
url("movies/Napoleon Dynamite/poster.jpg")
Ill post what I have so far, nothing happens on load. just a blank div with no background image :(.
$( '.video_selection' ).on( 'load', function() {
var backgroundimg = $( this ).attr('srcpost');
$( this ).css('background-image', backgroundimg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("movies/Napoleon Dynamite/poster.jpg")'>
<p>Napoleon Dynamite</p>
</div>

Please don't use element .onload method: Jquery on() load event on a single element. Might as well use $(document).ready(). Which would render your $(this) targeting window and you must change to element class. Also take care of \ in vidurl.
/*$(window).on( 'load', function() {
var backgroundimg = $('.video_selection').attr('srcpost');
console.log(backgroundimg); // << you can comment or delete this. only for demo purpose
$('.video_selection').css({'background-image': backgroundimg});
}); // window load will wait for all the content (images etc) to load before starting. */
$(document).ready(function(){
var backgroundimg = $('.video_selection').attr('srcpost');
console.log(backgroundimg); // << you can comment or delete this. only for demo purpose
$('.video_selection').css({'background-image': backgroundimg});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("movies/Napoleon Dynamite/poster.jpg")'>
<p>Napoleon Dynamite</p>
</div>
Also if you want to define multiple css value you can add them in {}:
$(document).ready(function(){
var backgroundimg = $('.video_selection').attr('srcpost');
$('.video_selection').css({'background-image': backgroundimg, 'height': '500px'});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")'>
<p>Napoleon Dynamite</p>
</div>

$(function(){
var backgroundimg = $('.video_selection').attr('srcpost');
$( '.video_selection' ).css('background-image', backgroundimg);
})
.video_selection {
width: 500px;
height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg")'>
<p>Napoleon Dynamite</p>
</div>

You can do like this for trigger load event for div.
$(function(){
$('div[onload]').trigger('onload');
});
function changebackground(div) {
var backgroundimg = $('.video_selection').attr('srcpost');
//alert(backgroundimg)
$('.video_selection').css('background-image', backgroundimg);
}
$(function(){
$('div[onload]').trigger('onload');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' onload="changebackground(this)" vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("https://cdn.pixabay.com/photo/2016/04/15/04/02/water-1330252__340.jpg")'>
<p>Napoleon Dynamite</p>
</div>

Related

How to add spinner in Jquery .html(<object data="http://example.com">)

I loading external website (my own) using Jquery.
<div id="siteloader"><center>
<img style="width: 100px; height: 100px;" src="http://seafood.greenpeaceusa.org/images/spinner.gif" alt="Mountain View" /></center></div>
​
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$( document ).ready(function() {
$("#siteloader").html('<object "width:100%; height:2000px; data="http://example.com/findex.php">');
});
</scirpt>
As you can see right now, I am loading spinner gif inside the div and replacing the content of the div with the external website html, However it is replacing it on the moment it is downloading the website can I make it wait untill the website is downloaded and only then replace the html ?
By the way, .load method is not working for me for some reason =\
Your object replaces content of the div at document.ready. It should be done when the object is loaded.
<script>
$( document ).ready(function() {
//$("#siteloader").html('<object "width:100%; height:2000px; data="http://example.com/findex.php">'); syntax errors here
//this doesn't work as well
$('<object "width:100%; height:2000px; data="http://example.com/findex.php">')
.load(function(){
$("#siteloader").empty().append(this);
});
});
</script>
Fixed working script:
<script>
$( document ).ready(function() {
/*
//wrong again spinner disappear before object loaded
$('<object style="width:100%; height:400px; display:none;" data="http://www.w3schools.com/tags/helloworld.swf" />')
.appendTo($("#siteloader"))
.after(function () {
console.log('loaded');
$(this).show().siblings().each(function () {
$(this).remove();
});
});
*/
//and this work for sure
var obj = document.createElement('object');
obj.onload = function () {
console.log('loaded');
$(this).css({ width: '100%', height: '400px' }).show()
.siblings().each(function () {
$(this).remove();
});
};
obj.data = 'json.php';
$(obj).appendTo('#siteloader');
});
</script>
I hope it will work with your data as well. This looks ugly (mix jquery and pure JS) but this is the only found way to make it work. $(obj).appendTo('#siteloader') triggers the load.
Just in case, PHP used:
<?php
usleep(10000000);
echo '{"name":"qwas","qty":10,"curr":"'.date('h:i:s').'"}';
?>

Getting the text element of group_name

<div class="group_list_table_row" group_id="10">
<div class="group_name">Name of Course</div>
<div class="group_list_edit_row" style="left: 215px;">
Click me.
</div>
</div>
<script type="text/javascript">
/* This triggers when update button is clicked. */
$( ".update_group" ).click(function(event) {
var value = $(this).parent().parent().text();
alert(value);
event.preventDefault();
</script>
I was trying to get the text only of group_name class which is "Name of Course". However, the result of alert(value) also includes "Click me." and "Name of Course". Need help on this.
You can do this easier:
<script type="text/javascript">
/* This triggers when update button is clicked. */
$( ".update_group" ).click(function(event) {
var value = $('.group_name').text();
alert(value);
event.preventDefault();
});
</script>
Try this:
$(".update_group").click(function(event) {
var value = $(".group_name").text();
alert(value);
event.preventDefault();
});
as long as the previous answers provide a proper solution you might be interested why yours does not work, and this is because the ".group_name" element is not a parent of the parent of your element, as you might expected. It is apparently not a parent at all, containing only plaint text inside.
Therefore the $(this).parent().parent() call returns the ".group_list_table_row" element, that contains the two other divs and it's text is the concatenation of their contents.
A some indentation and things will be obvious:
<div class="group_list_table_row" group_id="10"> /*parent 2*/
<div class="group_name">Name of Course</div>
<div class="group_list_edit_row" style="left: 215px;"> /*parent 1*/
Click me.
</div>
</div>

Displaying or Hiding Divs

I have read probably 50 articles that say how to hide or show div's depend on a click action. However, I have tried almost every approach and my div's do not hide or show. Seems likely I am missing something very basic.
<script>
$(document).ready(function(){
$('buynav').on('click',function(){
document.getElementById('buycontent').style.display = 'block';
document.getElementById('sellcontent').style.display = 'none';
});
$('sellnav').on('click',function(){
document.getElementById('buycontent').style.display = 'none';
document.getElementById('sellcontent').style.display = 'block';
});
});
</script>
<div id="contentContainer">
<div id="documentSpace" style="left: 50%; top: 50px">
<div id="headerPhoto" style="position:absolute;left:2.5%;width:95%; height:200px; background-image:url('../images/jpgHeader4.jpg'); background-size:cover;background-position:center; background-repeat:no-repeat;border-radius:9px; margin-top:17px;">
</div>
<div id="secondNav" style="position:absolute;left:2.5%;width:95%;height:75px;top:250px;text-align:center;vertical-align:middle;">
<div id="buynav" class="buynav"><h2>Buy</h2></div>
<div id="sellnav" class="sellnav"><h2>Sell</h2></div>
</div>
<div id="sellcontent" style="position:absolute;left:2.5%;width:95%;height:100%;top:350px;display:none;">
</div>
<div id="buycontent" style="position:absolute;left:2.5%;width:95%;height:100%;top:350px;display:block">
</div>
</div>
</div>
Use jQuerys show() and hide() as such:
<script>
$(document).ready(function(){
$('#buynav').on('click',function(){
$('#buynav').show();
$('#sellnav').hide();
});
$('#sellnav').on('click',function(){
$('#buynav').hide();
$('#sellnav').show();
});
});
</script>
Another option is to use jQuery's toggle(), but it requires you to have hidden one element before using it.
<script>
$(document).ready(function(){
$('#buynav').on('click',function(){
$('#buynav').toggle();
$('#sellnav').toggle();
});
$('#sellnav').on('click',function(){
$('#buynav').toggle();
$('#sellnav').toggle();
});
});
</script>
Also I added # in the $('#buynav') and other JS selectors. And, as #mdesdev, pointed out you can replace the document.getElementById('buycontent') with $('#buynav') and $('#sellnav') as they seem to "exist" within your jQuery scope.
I think you have forget to put # for your id.
$('#buynav, #sellnav').on('click',function(){
$('#buycontent').toggle();
$('#sellcontent').toggle();
});
Hope it works

Changing a div's id on click

How do I add an onClick listener to a div.
I want to change the name of a div to divclass active if it was inactive previously & then remove the word 'active' if user click on the list again.
I'm at a loss how to do this.
This is what I've tried so far
<script>
$function tog(){
$(this).toggleClass('active');
return false;
}
$(function() {
var dd = new DropDown( $('#dd') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-4').removeClass('active');
});
});
</script>
where the div whose class name I want to change is defined as below
<div id="dd" onclick="tog()" class="wrapper-dropdown-4">
<!--something-->
</div>
I've tried this..
<html>
<head>
<script>
$('#dd').on('click', function(){
$(this).toggleClass('active')
});
</script>
<style>
.active {
color: red;
}
</style>
</head>
<body>
<div id="dd" class="wrapper-dropdown-4">
ddddd
</div>
</body>
</html>
What's wrong with this now?
I'm inspecting the element id via chrome developer's tool & I don't see any change using this code. So, can anyone please help?
Thanks. :)
The only script you need is
$(function(){
$('#dd').on('click', function(){
$(this).toggleClass('active')
});
});
Demo: Fiddle
you have to pass the object $(this) is not recognizable , use tog(this)
<script>
function tog(obj)
{
$(obj).toggleClass('active');
return false;
}
$(function() {
var dd = new DropDown( $('#dd') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown-4').removeClass('active');
});
});
</script>
<div id="dd" onclick="tog(this)" class="wrapper-dropdown-4">
<!--something-->
</div>
not the best way to do it, you can bind the event ,by registering the click in the event.

Shortening my jQuery

How would I make this jQuery shorter? I assume there must be a better way of working than this!?
(bare in mind I am new to jQuery)...
<script>
jQuery(function() {
var White = jQuery("#white").hide();
jQuery("#firstpagename").on("click", function() {
White.toggle();
});
});
</script>
<script>
jQuery(function() {
var Black2 = jQuery("#v2black").hide();
jQuery("#secondpagename").on("click", function() {
Black2.toggle();
});
});
</script>
<script>
jQuery(function() {
var Black3 = jQuery("#v3black").hide();
jQuery("#thirdpagename").on("click", function() {
Black3.toggle();
});
});
</script>
Any help or directions would be greatt as I am down to the last step on this site and want it finished :)
You could use some extra data attribute and an extra class on your links to make it a little shorter.
So let's say your html looks like this:
<div id="white">white</div>
<div id="v2black">v2black</div>
<div id="v3black">v3black</div>
<div id="firstpagename" class="toggle" data-for="white">toggle white</div>
<div id="secondpagename" class="toggle" data-for="v2black">toggle v2bacl</div>
<div id="thirdpagename" class="toggle" data-for="v3black">toggle v3black</div>
then your jquery can rewritten like this:
jQuery(function() {
$('.toggle').on('click', function() {
var id = $(this).attr('data-for');
$('#' + id).toggle();
});
});
So it looks like we're trying to recreate standard "accordion" behaviour. Depending on the layout of your page, it can be helpful to encapsulate your items if possible. Here is one possible solution to make things that open and close. jsFiddle
<div id="white" class="panel">
<div class="tab"></div>
<div class="content"></div>
</div>
<div id="v2black" class="panel">
<div class="tab"></div>
<div class="content"></div>
</div>
<div id="v3black" class="panel">
<div class="tab"></div>
<div class="content"></div>
</div>​
<script>
jQuery(".tab").on("click", function() {
$(this).closest('.panel').find('.content').toggle();
});​
</script>
First we condensed the code into one script tag and one document ready statement, since having it in 3 pieces was only adding bloat.
Then I made sure to chose $ as the parameter for the doc ready callback. jQuery will kindly pass it one argument jQuery so inside our code block we can safely use $ even if outside our code-block it was reserved for other purposes.
Here the .tabs control their .content by traversing up to the nearest .panel and back down. In this way the same behaviour can control all 3.
If however your "tabs" can't be encapsulated like this you can always associate them to the content they are to show/hide in another way. We'll just need to see your html.
<script>
jQuery(function() {
var White = jQuery("#white").hide();
jQuery("#firstpagename").on("click", function() {
White.toggle();
var Black2 = jQuery("#v2black").hide();
jQuery("#secondpagename").on("click", function() {
Black2.toggle();
});
var Black3 = jQuery("#v3black").hide();
jQuery("#thirdpagename").on("click", function() {
Black3.toggle();
});
});
</script>
for the start. If you have many more elements, you might want to loop through a buttonid<>toggleid map:
var map = {
"white": "firstpagename",
"v2black": "secondpagename",
...
};
for (var toggler in map)
makeToggle(toggler, map[toggler]);
function makeToggle(togglerid, pageid) {
var page = $(document.getElementById(pageid)).hide();
$(document.getElementById(togglerid)).click(function() {
page.toggle();
});
}

Categories