Javascript onClick change background picture of div - javascript

My ultimate goal is to change the background of a div through clicking on the sampla picture.
First I wrote this:
<a onclick="document.getElementById('sp').style.background="url('/assets/castle.png')"">...<a>
but it didn't work. I noticed that the problem was usage of multiple " and '. So put the function into a script tag:
<script type="text/javascript">
var pic="";
function showP(pic) { document.getElementById('sp').style.background='url(pic)';};
</script>
<a onclick="showP(/assets/castle.png)"><img src="/assets/castle.png" width="50px" height="50px"></a>
As supposed by seeing /assets dir, this is a rails app. I also tried o use jQuery selectors like $("#sp").css() or dropping the variable altogether and trying the function as:
function showp1() { document.getElementById('sp').style.cssText='background: transparent url(/assets/castle.png) no-repeat 0 0;'}
to try out solutions proposed in questions with similar titles but none did work. Whatever I try, on the html source, the portion showP(/assets/castle.png)" below is marked red:
<a onclick="showP(/assets/castle.png)"><img src="/assets/castle.png" width="50px" height="50px"></a>
Are there any suggestions?

Avoid putting JS in your HTML code. Use unobtrusive event listeners. They are very easy in jQuery:
$('#clickMe').on('click', function() {
$('#changeMe').css('background-image', 'url(http://placehold.it/200x200/ff0000)');
})
See this Fiddle.

Try this:
<script type="text/javascript">
function showP(pic) {
document.getElementById('sp').style.background = 'url(' + pic + ')';
};
</script>
<a onclick="showP('/assets/castle.png')">
<im src="/assets/castle.png" width="50px" height="50px" />
</a>
You needed to pass a string to the showP function in the onclick handler, which should be in quotes. You're passing a string into the function, which is in the pic variable being passed into the function. You want that string variable's value to be concatenated with the URL rule for the background style.

the background image URL does not require quotes. Try:
<a onclick="document.getElementById('sp').style.background='url(/assets/castle.png)'">...<a>

As others have said, you do seem to have an issue with quotes. You can check out my working example on jsFiddle.

Related

Javascript: image onclick then slide big image

I really like this slider sample HERE!. But I want to do is assign next/previous onclick command on images display on right side like this:
Instead of clicking those DOTS. I want to assign the onclick EVENT on images(RED BOXES).
How can I tweak that one.
Thank you in advance!
I've simply changed the $navDots variable to point to the images on line 90 of js.
var navDots = $('.nav-images');
this.$navDots = navDots.children( 'img' );
Then use this HTML:
<div class="nav-images">
<img src="http://lorempixel.com/400/200/city" alt="img01" width="100px"/>
<img src="http://lorempixel.com/400/200/business" alt="img02" width="100px"/>
<img src="http://lorempixel.com/400/200/technics" alt="img03" width="100px"/>
<img src="http://lorempixel.com/400/200/people" alt="img04" width="100px"/>
<img src="http://lorempixel.com/400/200/nature" alt="img05" width="100px"/>
<img src="http://lorempixel.com/400/200/sports" width="100px"/>
</div>
Hope it helps! Please see codepen example as well!. http://codepen.io/anon/pen/corjw
Disclaimer
Please do link to the non-minified source of the plugin, so you can modify that file directly. Currently, the plugin handles all the elements inside the #cbp-fwslider area. It may not be advisable to hack from outside, which is what this solution is...
Solution
It looks like you can mimic this by hiding the dots (which is what the plugin uses by default) and using your two elements to trigger click events on the dots. The currently active dot is indicated by a cbp-fwcurrent, so something like $('#cbp-fwslider .cbp-fwdots .cbp-fwcurrent') would select the current dot. Use jQuery's next() and prev() calls check if the relevant dot exists, and then do a $el.trigger('click').
Code Outline (untested)
$('#fwdButton').click(function() {
var $dot = $('#cbp-fwslider .cbp-fwdots .cbp-fwcurrent'),
$nextDot = $dot.next();
if ($nextDot) {
$nextDot.trigger('click');
}
});
`

Easy way to set font color in javascript onClick?

Question: So let's say I have some basic code
<a name = "sec">this is a test</a>
I want a javascript function to on click of a link to change that to
So user clicks:
link!
And the JS kicks in to change the 1st html to:
<font color = "green"><a name = "sec">this is a test</a></font>
Is it possible to do this in JS?
You can set the element's color with JS as a simple solution. You should also give the element a valid href attribute that nullifies the default click behavior.
<a name="sec" href="javascript:void(0);" onclick="this.style.color='green';">
this is a test
</a>
Try something along the lines of
link
And you should not use <font> tag for setting text attributes, this is considered bad practice in today’s HTML (be it XHTML or HTML5).
Something like this should work: (Psudeo Code)
<a id="sec" onClick="makeGreen()">this is a test</a>
<script type="text/javascript" charset="utf-8">
function makeGreen() {
document.getElementById('sec').style.color('green');
};
</script>
Realistically, you should keep your semantics and your style separate. As other users have suggested, use a css class instead of modifying styles directly. This is fairly easy to do, as shown by this jsFiddle
This is a test
<script type="text/javascript">
var el = document.getElementById('my-link');
el.addEventListener('click', function() {
this.className = 'clicked-class';
});
</script>
And of course in your CSS you would define some sort of rule:
.clicked-class {
color: green;
}
This could be made even simpler with a javascript library of your choice, but hopefully should be enough to get you started.
$(element).on("click",function() {$(this).css({'color', 'blue'});

jQuery Multiple Attribute Selector, Not Working :/

As far as I know, I'm following the correct usage form on: http://api.jquery.com/multiple-attribute-selector/, but for whatever reason I'm not seeing, my code is not working. Each attribute works fine independently of one another (i.e.
$(".tonight_stat_peopleThumbs li[srcid="+srcid+"]") works and $(".tonight_stat_peopleThumbs li[style*=inline-block]") works) but they do not work together.
Here is my function in the JavaScript:
hidePatrons = function(srcid) {
$(".tonight_stat_peopleThumbs li[srcid="+srcid+"][style*=inline-block]").each(function(){
$(this).css({"display" : "none"});
});
}
Here is a piece from the HTML:
<ul activepage="1" class="tonight_stat_peopleThumbs" style="width:171px">
<li id="myid" class="myclass" ptype="people" ptime="11101101" style="display:inline-block;">
<a href="http://domain.com/users/#.php">
<img src="https://graph.facebook.com/#/picture" />
</a>
</li>
</ul>
NOTE: The '#' are inserted for privacy, assume they are fbid numbers.
Note that while CSS allows attribute selectors without quotes, there are quotes in every jQuery example. My experience has been that jQuery does not select reliably without quotes.
/* Good for CSS, bad for jQuery */
[foo=bar]
/* Good for both */
[foo="bar"]
Try
$('.tonight_stat_peopleThumbs li[srcid="' + srcid + '"][style*="inline-block"]')
mind the quoting!
try changing li[srcid="+srcid+"] to li[id="+srcid+"] I don't see a "srcid" attribute so I assume you are looking to search on the "id" attribute
can you please try like this way? the following is working fine for me for your HTML code.
hidePatrons = function(srcid) {
$("#tonight_stat_peopleThumbs li[ptype=people][style*=inline-block]").each(function(){
$(this).css({"display" : "none"});
});
}
note: # is for id, and . is for class. I changed . to # and srcid="+srcid+" to ptype=people from your code.

html anchor tag reference

i have an anchor tag as below.
<a style="border:0px" href='javascript:deleteAttachment(this);' />
Inside the deleteAttachment, how can i get the anchor tag. Sending this to the method, sends the window element to the method.
function deleteAttachment(ancElement){
//Jquery operation on acnElement
}
Please helop me out.
I would recommend a slightly different approach, since what you're trying to do is a bit old.
assuming you already loaded jQuery, here we go:
<a id="myFirstLink" href="someHref" />
<a class="otherLinks" href="secondHref" />
<a class="otherLinks" href="thirdHref" />
<script>
$(function() {
$('#myFirstLink, .otherLinks').click( function(event) {
// stops the browser from following the link like it would normally would
event.preventDefault();
// do something with your href value for example
alert( $(this).attr('href') );
});
});
</script>
So basically what you can do is this: simply generate all your anchors like you would normally would and apply the same class name to each of them - in my example the class would be "otherLinks".
After that, all your links will be handled by that anonymous function.
Use the onclick handler:
<a onclick="deleteAttachment(this)">
or, the cleanest and most accepted method nowadays, have just the raw link in the HTML:
<a id="deleteAttachment">
and add the click event programmatically, in a separate script block, on DOM load:
document.getElementByID("deleteAttachment").onclick =
function() { ... you can use "this" here .... }
you must set its ID attribute
<a id="myAnchor" style="border:0px;" href="javascript:deleteAttachment('myAnchor');"/>
then use jquery to find it
function deleteAttachment(ID)
{
var MyAnchor = $('#'+ID);
}

inline javascript in href

How can you do something like this:
<a href="some javascript statement that isn't a function call;" >myLink</a>
And have the js in the href execute when the link is clicked.
Just put the JS code directly in there:
fsljk
Though, you should not be doing inline scripting. You should unobtrusively attach event handlers.
<a id="lol" href="/blah">fdsj</a>
<script>
document.getElementById('lol').onclick=function() {
/* code */
};
</script>
<a href="javascript:var hi = 3;" >myLink</a>
Now you can use hi anywhere to get 3.
You can write inline-code in the same way as
<a href="javascript:[code]">
This method is also available in other tags.
addition
if you want to Execution when something tag clicking, you can fix with onClick attribute
<a onClick="function()">
I know this question is old but I had a similar challenge dynamically modifying the href attribute that sends an email when the anchor tag is clicked.
The solution I came up with is this:
$('#mailLink,#loginMailLink,#sbMailLink').click(function () {
this.setAttribute('href', "mailto:" + sessionStorage.administrator_mail_address + "?subject=CACS GNS Portal - Comments or Request For Access&body=Hi");
});
<a id="loginMailLink" href= "#" style="color:blue">CACS GNS Site Admin.</a>
I hope that helps.

Categories

Resources