Trying to use Javascript to change img src in HTML - javascript

I'm trying to use Javascript to change the src attribute of an image (id: big-img) to that of a smaller image (class: clicky) when the smaller image is clicked to create . Unfortunately it doesn't seem to be working. Code provided below.
HTML:
<!DOCTYPE HTML>
<html lang="en">
<head>
<!-- Always use meta tags in head first -->
<!-- Sets character encoding (utf-8 = unicode) -->
<meta charset="utf-8">
<!-- Sets width of the page to width of the device and sets initial zoom
value to 1.0. Used for mobile viewing -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Linking in bootstrap (css) and author styles. -->
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="css/styles.css">
</head>
<body>
<!-- For simple Javascript concept exercises -->
<div id="practice">
<p>
Does this work?
</p>
</div>
<!-- For image related complex(ish) Javascript exercises -->
<div class="container">
<div class="row">
<div class="clicky col-md-3"><img src="img/img1.jpg"></div>
<div class="clicky col-md-3"><img src="img/img2.jpg"></div>
<div class="clicky col-md-3"><img src="img/img3.jpg"></div>
<div class="clicky col-md-3"><img src="img/img4.jpg"></div>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<img id="big-img"
class="large-img"
src="img/img1.jpg">
</div>
</div>
</div>
<!-- <div class="col-md-12">
<img id="bigImage"
class="large-img"
src="img_1.jpg"
alt="graffittied building"/>
</div> -->
<!-- Linking in Jquery library, bootstrap (JS) and my scripts. Imported in
that order due to bootstrap requiring some Jquery features so needs to be
lower in source order -->
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
</body>
</html>
Javascript:
$(".clicky").click(function(){
$("#big-img").attr('src',
$(this).attr('src'));
});

As clicky is not img element it doesn't have src attribute thus the code is working as expected.
You need to traverse to img element the fetch its attribute, there are various ways to achieve that. Here in code I have used .find() method since img is child of clicky element
$(".clicky").click(function(){
$("#big-img").attr('src', $(this).find('img').attr('src'));
});
OR, You can bind event with img element then your code will work
$(".clicky img").click(function(){
$("#big-img").attr('src', this.src);
//$("#big-img").attr('src', $(this).attr('src'));
});

function change_img(){
$(document).on("click",".clicky img",function(){
var el = $(this);
var src = $.trim(el.attr("src"));
(src !=="") ? $("#big-img").attr("src",src) : '';
});
}
$(function(){
change_img();
});

Try this:
$(".clicky").click(function(){
$("#big-img").attr('src',
$(this).find('img').attr('src'));
});

clicky class is attached to a div not to an img so it does not have a src attribute
What you can do is this:
$(".clicky > img").click(function(){
$("#big-img").attr('src', $(this).attr('src'));
});
But if you want to to attach the listener on the div, you can do this:
$(".clicky").click(function(){
$("#big-img").attr('src', $(this).find("img").attr('src'));
});

$(this) refers to the clicked element : <div>. You need to get img thats inside the div.
$(".clicky").click(function(){
$("#big-img").attr('src',$('img', this).attr('src'));
});
To complete :
$(".clicky").on('click', function(e){
$("#big-img").attr('src',$('img', this).attr('src'));
});

Related

Inject css inline into elements using js

For example, my html code is as follows:
<html lang="en">
<head>
<meta charset="utf-8">
<title>add style inline in js</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="one">
<div class="two">
link
</div>
</div>
<script src="js/my-scripts.js"></script>
</body>
</html>
I want to select elements and style them in my-scripts.js file like css:
.one .two a:hover{color:red;}
I have a sample jquery code:
function injectStyles(rule) {
var div = $("<div />", {
html: '­<style>' + rule + '</style>'
}).appendTo("body");
}
$("button").on("click", function() {
injectStyles('a:hover { color: red; }');
});
https://css-tricks.com/snippets/javascript/inject-new-css-rules/
but I want to do this without using jquery and without using the button.
(Apply styles after loading script file)
I want to define my css code in js and define each one separately as "inline" for each element.
Thanks to the professors
You could create a template class in your css file like this
.colorOnHover a:hover {
color: red;
}
And then you can use document.querySelector to get the element and add the colorOnHover to the classList of that element.
// your js file
const element = document.querySelector(''); // pass in the ID or the class of the element you want to add the changes to
(function() {
element.classList.add('colorOnHover');
})();
// this will add `colorOnHover` class to the classList and apply the css defined to the class in your css file.
Make sure to link the javascript & css file (if any) using <script src = "pathHere" defer></script> and <link rel = 'stylesheet' href = "pathHere>" respectively
update : since the op didn't want to use querySelector
You could use document.createElement('style') and append it to the html file, it would be similar to manually inserting a tag
(function() {
const styleEl = document.createElement('style');
styleEl.textContent = '.one .two a:hover{color:red;}';
document.head.append(styleEl);
console.log('added new style tag');
})();
This how to inject your CSS to to <style> tag :
JS & jQuery code :
function injectStyles(rule) {
$("style").append(rule);
}
$("button").on("click", function() {
injectStyles('.one .two a:hover{color:red;}');
});
HTML code :
<html lang="en">
<head>
<meta charset="utf-8">
<title>add style inline in js</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="one">
<div class="two">
link<br>
<button type="button">Make the link hover Red</button>
</div>
</div>
<script src="js/my-scripts.js"></script>
</body>
</html>

Do the exact contrary of append in Jquery

I'm working on a 3D interface with Babylonjs, so I need a canvas. Around that canvas I want to implement html elements (with Holy grail layout : nav to the left, main which is canvas at the middle and aside to the right) according to 2 modes : visualisation and edition.
I have a script to handle the canvas and play with babylonjs functions, and another one to manage the construction of the html according to the chosen mode.
As you can see in my code, I assign my html code to a variable, and append that variable to my holygrail main. However, I don't want my canvas to be recreated each time I change mode, so I implemented it directly in the HTML, it's constant.
My problem is : I want to append elements to my div #insertHere, but also to remove all the elements (excepted my canvas which has to remain) of this #insert div before appending new ones (else I would have several navs and asides).
Can anyone help me ?
Thank for your time !
Here's my construction script :
var content = "";
var construct = true;
var visualize = false;
function Create(){
content = "";
if(construct == true && visualize == false){
content += "<div id='1'> <p> hello</p></div><div><p>Insert a lot of html here</p></div>";
$("insertHere").append(content);
}
if(construct == false && visualize == true){
content += "<div id='not1'><p> Definitely not the same content as the construct one</p></div>";
$("insertHere").append(content);
}
}
$(window).ready(function(){
Create();
$("#switchmode").click(function(){
construct = !construct;
visualize = !visualize;
// INSERT THE SOLUTION TO CLEAR THE HTML HERE
CreationPage();
});
});
And here's my HTML (both are short representation of what I really have) :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
</head>
<body id="body" class="HolyGrail">
<header>
<link rel="stylesheet" type="text/css" href="style.css" media="all">
<link rel="stylesheet" href=".\bootstrap\css\bootstrap.css">
<link rel="stylesheet" href="justcontext.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" defer></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<script style="text/javascript" src="scripts/construction.js" defer></script>
</header>
<div id='menuonglets' class='btn-group' role='group' aria-label='Basic example'>
<button type='button' class='btn btn-secondary' id='switchmode'>Mode Visu/ Mode Constru</button>
</div>
<div class='HolyGrail-body' id='insertHere'>
<main class='HolyGrail-content'>
<canvas id='renderCanvas'></canvas>
</main>
<!-- Things are inserted here -->
</div>
</body>
</html>
You could use jQuery's filter() function to remove all elements but the canvas.
Here's a working example:
$("#btn_clear").on("click", function(e){
e.preventDefault();
$("#insertHere").children().filter(":not(.HolyGrail-content)").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='HolyGrail-body' id='insertHere'>
<main class='HolyGrail-content' style="background: orange;">
<canvas id='renderCanvas'></canvas>
</main>
<p>I'm a paragraph</p>
<ul>
<li>Foo</li>
<li>bar</li>
</ul>
</div>
Remove all elements but the canvas
So:
$(window).ready(function(){
Create();
$("#switchmode").click(function(){
construct = !construct;
visualize = !visualize;
// Remove all elements, except for the canvas and its container.
$("#insertHere").children().filter(":not(.HolyGrail-content)").remove();
CreationPage();
});
});

Why is my jQuery script written in notepad++ not working on files stored locally?

I tried to do a simple slider but that did not work, so i am copying one of code cademy, but it still qont work.
I have used 4 different browsers all have the same problem, i can type in the box but wont post, and show below.
PLEASE HELP?
Html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp2/css/bootstrap.min.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<link type='text/css' href="stylesheet.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<textarea class="form-control status-box" rows="2" placeholder="What's on your mind?"></textarea>
</div>
</form>
<div class="button-group pull-right">
<p class="counter">140</p>
Post
</div>
<ul class="posts">
</ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
AMMENDED
script.js
$(document).ready() {
$('.btn').click(function() {
var post = $('.status-box').val()
$('<li>').text(post).prependTo('posts');
});
};
THANK YOU ALL, this has been corrected and it now works :)
val is a jQuery function ... you need () to invoke it so it returns the value of element. As your code stands now you are trying to set a function object as text.
You are also using incorrect selectors $('btn') and $('status-box') which are looking for non existent tags <btn> and <status-box>.
Add dot prefix for both to represent class:
$('.btn') and $('.status-box')
As well as what's been mentioned in the other answer, I don't believe your main method is ever called. If it isn't called then the event handler isn't going to be attached.
The main method would be easier set up via jquery, so instead of:
var main = function() {
$('btn').click(function() {
var post = $('status-box').val
$('<li>').text(post).prependTo('.posts');
});
}
Just do:
$(function() {
$('btn').click(function() {
var post = $('status-box').val
$('<li>').text(post).prependTo('.posts');
});
});
Alternatively you could adjust your body tag as follows:
<body onload="main()">

How to loop 3 divs with jQuery

I need a little help looping multiple divs (3 or more) using jQuery. The look I am after is having my home page rotate its main image div with other divs so that both the background image (of the div only) changes as well as links contained within the div.
I had created the effect with stacking CSS and fading in to an image behind, however now I also require the links in the div to change.
This is the HTML for the section -
<head>
<title>Sample</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.leanModal.min.js"></script>
<link type="text/css" rel="stylesheet" href="index.css" />
</head>
Now the Div that I want changing
<div class="jumbotron-1">
<div class="container">
<h1>What We Are</h1>
<p> A Paragraph</p>
<div class="divbutton">
Learn more
</div>
</div>
</div>
<div class="jumbotron-2">
<div class="container">
<h1>What We Are</h1>
<p> A Paragraph</p>
<div class="divbutton">
Learn more
</div>
</div>
</div>
<div class="jumbotron-3">
<div class="container">
<h1>What We Are</h1>
<p> A Paragraph</p>
<div class="divbutton">
Learn more
</div>
</div>
</div>
I found a similar code to what I am after :
var slideShowDivs = ['.jumbrotron-1', '.jumbotron-2', '.jumbotron-3'];
var currentID = 0;
var slideShowTimeout = 1000;
$(document).ready(function() {
for (var i = 1; i < slideShowDivs.length; i++) $(slideShowDivs[i]).hide();
setTimeout(slideShowChange, slideShowTimeout);
});
function slideShowChange() {
var nextID = currentID + 1;
if (nextID >= slideShowDivs.length) nextID = 0;
$(slideShowDivs[currentID]).stop(true).fadeOut(400);
$(slideShowDivs[nextID]).stop(true).fadeIn(400, function() {
setTimeout(slideShowChange, slideShowTimeout);
});
currentID = nextID;
}​
But it doesnt seem to work.
Any additional thoughts?
Try jquery each insted of for loop
$('.jumbrotron-1,.jumbotron-2,.jumbotron-3').each(function() {
$(this).hide();
setTimeout(slideShowChange, slideShowTimeout);
});
jsfiddle: http://jsfiddle.net/66Lz2xou/2/
or
$('div[class^="jumbrotron"]').each(function() {
$(this).hide();
setTimeout(slideShowChange, slideShowTimeout);
});
http://jsfiddle.net/66Lz2xou/3/
Sorry I need 50 reputation to comment, but I wanted to go off of #ARUN BERTILs answer.
You could put the divs in a array like:
var div_array = ['.jumbotron-1', '.jumbotron-2', '.jumbotron-3']
jQuery.each(div_array,function(i, val){
/* What you want each one to do*/
//example
$(val).css('background','blue');
})
Hi the best approach is to use this approach
$( "div" ).each(function( i ) {
//Your condition
} });
use class selectors
$(".jumbotron-1 .jumbotron-2 .jumbotron-3").each(function( i ) {
//process your code here
} });
or if you want child container divs attach > container to each of the selectors like .jumbotran-1 > container

Show image via javascript after page load

I am trying to create an image which is initially hidden - but reveals itself once the document has loaded completely via the JavaScript file.
$(document).ready(function () {
document.getElementById("theImage").style.visibility = "visible";
});
#theImage {
visibility:hidden;
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kami Nelson Bio </title>
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="KNelson-Styles.css" rel="stylesheet" type="text/css">
<script src="respond.min.js"></script>
<script src="KNelson_reveal.js"></script>
</head>
<body>
<div class="gridContainer clearfix">
<div id="theImage">
<img src="images/Kami-100.jpg" alt="Kami Nelson Image"/>
</div>
<div id="div1" class="fluid">
<h1>Bio for Kami Nelson</h1>
<p>Text</p>
</div>
</div>
</body>
</html>
Why is this not working?
Thank you in advance.
You should either include jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or use native window.onload() instead of $(document).ready()
window.onload=function () {
document.getElementById("theImage").style.visibility = "visible";
}
You are missing the jQuery library reference
You are not properly
using selecter to select image of id theImage.
theImage is supposed to be for the img tag.
JavaScript
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$("#theImage").css('display':'block');
});
</script>
CSS
#theImage {
display: none;
}
HTML
<img id= "theImage" src="images/Kami-100.jpg" alt="Kami Nelson Image"/>
why don't you just draw the image when the window loads?
give your image an id i'll use "image" for this example.
<script>
window.onload = function ()
{
$('#image').css({"display":"block";});
}
</script>

Categories