retrieve background image from css using javascript without using it's ID - javascript

I've looked around and it's been hard to find a thread that does what I want it to do. As far as I am concerned, I don't even know if it's possible. What I am looking to do is to retrieve the background image file name (especially if it is a link) when it is click. I have a script that logs all click but the last piece I need is the background-image name (file-path with name would even do) stored in the CSS file. Anyone have an idea or a solution as to how this can be done without using a div or class? Here's what I have right now:
JavaScript & HTML
<script type="text/javascript">
var arrayWithElements = new Array(); //,replaytimer;
document.onclick = clickListener;
function clickListener(e)
{
var clickedElement=(window.event)
? window.event.srcElement
: e.target,
tags=document.getElementsByTagName(clickedElement.tagName);
for(var i=0;i<tags.length;++i)
{
if(tags[i]==clickedElement)
{
if(clickedElement.tagName=="A")
{
arrayWithElements.push({tag:clickedElement.tagName,index:i});
console.log(clickedElement.baseURI,clickedElement.href,clickedElement.innerText,document.location.href,document.images.href);
}
if(clickedElement.tagName=="IMG")
{
arrayWithElements.push({tag:clickedElement.tagName,index:i});
console.log(clickedElement.baseURI,clickedElement.parentNode.href,clickedElement.innerText,document.location.href,document.getElementsById(element).src);
}
if(clickedElement.tagName=="DIV")
{
arrayWithElements.push({tag:clickedElement.tagName,index:i});
console.log(clickedElement.baseURI,clickedElement.parentNode.href,clickedElement.innerText,document.location.href,document.getElementsById(element).src);
}
if(clickedElement.tagName=="CLASS")
{
arrayWithElements.push({tag:clickedElement.tagName,index:i});
console.log(clickedElement.baseURI,clickedElement.parentNode.href,clickedElement.innerText,document.location.href,document.getElementsById(element).src);
}
}
}
}
</script>
</head>
<a id="1" href="#">trial1</a>
<a id="2" href="http://www.google.com" target="blank">google</a>
<a id="3" href="http://www.google.com">google</a>
<a id="4" href="http://www.google.com" target="_blank"><img id="image" src="untitled.jpg"/></a>
<a id="5" href="trial.html">
<input type="text" id="text-test"/>
<div id="image-link"></div>
CSS:
#image-link {
background-image:url('untitled.jpg');
width: 50px;
height:50px;
border: 1px solid #000000;
}
This is a test file that will be converted for use in the near future. Thanks

On newer browsers, you can use window.getComputedStyle(clickedElement) to find the background image property.

As per your code, just the filename or the path using JQuery in all browsers:
var withId = $("#image-link").css("background-image").split('(')[1].split(')'),
withoutId = $("img").attr("src");
// with id and css file
console.log(withId[0]);
// without id and inline style
console.log(withoutId);

Yes, as Alnitak says, use getComputedStyle, but for compatibility with more browsers check out this other question:
Get element CSS property (width/height) value as it was set (in percent/em/px/etc)
Note: I would love to be able to comment on another user's good answer instead of posting my own that is pretty much the same but with a little additional info. Unfortunately, I cannot because stackoverflow doesn't permit this for a user with less than 50 rep. So I have to post it like this instead.

Related

Javascript.. Disable a #div using pure JS?

I've searched stackoverflow and gone through many pages deep in google. Nothing helped me to disable my button. So I come here wishing someone can help me.
Here's the button I'm trying to disable.
EDIT: This is different than the surposed dublicate as you said yourself, this is a div with a link and not a button.
<div class="de elBTN elAlign_center elMargin0 ui-droppable de-editable" id="button-80437" data-de-type="button" data-de-editing="false" data-title="button" data-ce="false" data-trigger="none" data-animate="fade" data-delay="500" style="margin-top: 30px; outline: currentcolor none medium; cursor: pointer; display: block;" data-elbuttontype="2" aria-disabled="false" data-element-theme="customized">
<a href="#" class="elButton elButtonSize1 elButtonColor1 elButtonRounded elButtonPadding2 elButtonCorner3 elBtnHP_25 elBTN_b_1 elBTNone elButtonBlock elButtonFull elBtnVP_5 elButtonShadow5 elButtonTxtColor1 de1pxLetterSpacing no-button-effect" style="color: rgb(255, 255, 255); background: rgb(1, 116, 199);; font-size: 20px;" data-show-button-ids="tmp_paragraph-42317,headline-29302" data-hide-button-ids="headline-71892,button-80437" id="undefined-503">
<span class="elButtonMain">YES</span>
<span class="elButtonSub" style="font-size: 14px;">I Understand</span>
</a>
</div>
This is what I'm trying to do.
ver = iOSversion();
if (ver[0] <= 11.4) {
alert('Your OS is below 11.4, please use a different device.');
document.getElementById('button-80437').disabled = true;
}
function disableEnable(elems, isDisabled){
for(var i = elems.length-1;i>=0;i++) {
elems[i].disabled = isDisabled;
}
}
tried with these aswell.. nothing.
var div = document.getElementsById("button-80437");
disableEnable(div.getElementsByTagName("button"), true);
EDIT: Thanks for your answers. I appreciate it. Unfortunatly there isn't much I can do to change it to a button as its made using a wysiwyg "clickfunnels".
Maybe I could do this instead.
How do I disable a href link in JavaScript?
Inject href="javascript: void(0)" ?
The div element does not have a disabled attribute. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div
If you use a button instead, you would be able to set the disabled attribute to disable the button. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
It looks like you might be using a framework that wants you to disable buttons in a different way. It would help if you included that information.
i got what you are trying to do.So listen
1) "disabled" works on Buttons
2) What you have is "not a button" but "a hyperlink inside div"
3) so what can you do?
you got to play with the styles to show that your "joker button" is disabled
if( version < 11.4 ) {
// make element div style looks like its disabled
// <a href="#">
}
else{
// make element div style looks like it is active
// <a href="<your-link-url>"
}
Like Jorge said, the main problem in your code is you’re trying to disable a non-formelement.
You can either:
Disable the <div> you have by putting the CSS pointer-events: none on your HTML-element *
Change your <div> into a <button> (which is a form-element) and use your current approach (setting the disabled property in Javascript)
* You can find browser-support information on pointer-events here: https://caniuse.com/pointer-events

How to manipulate iframe objects using jquery

I've gone through lot of topics related to this question but unable to get the desired output.
I'm calling a iframe inside and html like this:
<iframe class="full-screen-preview__frame" id="nitseditpreview" src="himu/index.php" name="preview-frame" frameborder="0" noresize="noresize" data-view="fullScreenPreview">
Suppose in this iframe I have h2 tag with a class name like this:
<body>
<section id="about-us">
<div class="container">
<div class="text-center">
<div class="col-sm-8">
<h2 class="maincontent">
Why with Us
</h2>
</div>
</div>
</div>
</section>
</body>
As seen by the inspect element in browser
By using Jquery I want to manipulate this lets say for example I want to put border in this. I've tried a lot of things but I guess this thing will work if anyone fixes the bug, my jquery looks like this:
$(document).load(function () {
$('#nitseditpreview').load(function () { //The function below executes once the iframe has finished loading
$this = $(this);
$('#nitsmenu', this.contents()).css('border', 'solid 1px #777');
});
});
Don't know where I'm doing mistake, even I'm following same origin policy too.
If both framed and framing documents are on the same domain, there shouldn't be any need for sandbox attributes or CORS hoop-jumping. But there are a number of other errors here:
$(document).load(...) should be $(document).ready(...) (since it has already loaded by the time your script runs)
you define $this = $(this), but then in the next line try to use a bare this
You're trying to match a #nitsmenu that doesn't appear to exist in the framed document
The following appears to work, although I'm concerned there may still be a race condition on that iframe's .load():
$(document).ready(function() {
$('#nitseditpreview').load(function() {
$(this).contents().find('.container').css('border', 'solid 1px #777');
});
});
http://plnkr.co/edit/tCEHdU0ckg5q4w4tPVFU

My div show/ hide code works fine on a static HTML page but doesn't work on a Wordpress 3.5.1 page

This is sort of a condensed version of the code, the real version is too long to post but this is enough to represent the concept. I am using this to switch guitar diagrams based on several choices represented by anchors with the corresponding id in the href="". After spending several days getting it to work just right on a static html page, the script won't work in a Wordpress page which is where I intend to use it. I have tried it with the script in the head or inline (which shouldn't matter) - but either way it will not function. I know that Wordpress and certain plugins use Jquery so there may be a version mismatch causing conflicts. I am not (yet) an expert in javascript but I know there are several ways to skin a cat as the saying goes, I just need to find one that plays nice with Wordpress. Any help would be greatly appreciated...
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var divswitch = $('div.diagram_container a');
divswitch.bind('click',function(event){
var $anchor = $(this);
var ids = divswitch.each(function(){
$($(this).attr('href')).hide();
});
$($anchor.attr('href')).show();
event.preventDefault();
});
});
</script>
<style>
.diagram {
margin: 0;
width: 100%;
}
.diagram_container {
width: 100%;
}
</style>
<div id="RH_RW_Div" class="diagram_container" style="float:left; display:block;">
<div class="diagram_menu">
<a class="checked" href="#RH_RW_Div"><span class="checkbox_label">Right Handed</span></a>
<a class="unchecked" href="#LH_RW_Div"><span class="checkbox_label">Left Handed</span></a>
</div>
<img class="diagram" src='images/RH_RW.gif' /><br />
</div>
<div id="LH_RW_Div" class="diagram_container" style="float:left; display:none;">
<div class="diagram_menu">
<a class="unchecked" href="#RH_RW_Div"><span class="checkbox_label">Right Handed</span></a>
<a class="checked" href="#LH_RW_Div"><span class="checkbox_label">Left Handed</span></a>
</div>
<img class="diagram" src='images/LH_RW.gif' /><br />
</div>
Wordpress uses by default jQuery.noConflict(). This is to assure that there is no conflict by other libraries using the $ variable. That's why your console says it's not a function.
However, obviously, the jQuery variable still works, and you should use that, and passing to your function the $ variable yourself to enable the shorthand version of jQuery.
So your code should look like this:
jQuery(document).ready(function($){
// Your functions go here
});
My guess is that your Wordpress install or a plugin is already loading up jQuery in the head. Check to see if it exists there, and if it does, don't call it again.
If that doesn't do it and you have this site online, send me the link and I'll take a look.
Calling jQuery twice will often lead to problems. There is also a proper way to load jQuery and override the Wordpress version if you specifically need 1.8.3 (wp_register_script and wp_enqueue_script), but I don't think you need to go down that route yet.

HTML/JS: Confused about method to create an image button

I need to create a simple button made only of an image, and which will open a JQuery Dialog when the user clicks on it.
I am doing some reading and notice many solutions: <button>, <image> with a <a>, using CSS to modify a button background, etc...
This is confusing, what is the proper way to implement my image button?
Thanks.
P.S.: The button/image should be focussable. An operational JSFiddle example is welcome.
The proper way largely depends on what the button will do if JavaScript is not available.
If you are going to submit a form then:
<button> <img src="..." alt="..."> </button>
If you are going to go to a URL then:
<img src="..." alt="...">
If you are going to do absolutely nothing (generally not a good idea, you should follow the principles of Progressive Enhancement and Unobtrusive JavaScript, but acceptable if you only generate the button with JavaScript in the first place and the loss to the user is convenience rather then essential functionality):
<button type="button"> <img src="..." alt="..."> </button>
You then bind the JavaScript to either the form's submit event, or the button/anchor's click event and prevent the default behaviour so the form won't be submitted / the link won't be followed if the JavaScript executes successfully.
Create a button and put background-image for it.
Checkout the fiddle.
http://jsfiddle.net/siyakunde/Y38nz/
I found the solution after many struggles: http://jsfiddle.net/YRY8M/3/.
<html>
<head></head>
<body>
<input type="image" tabindex="0" onclick="doSomething()" src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/White_and_yellow_flower.JPG/320px-White_and_yellow_flower.JPG"
/>
<br />
<button tabindex="1">I am focussable too !!!</button>
</body>
</html>
And some javascript:
function doSomething() {
alert('Hello!');
}
It depends on what you want to do in every case. There is no guideline that says "you should do it like this", but there are situations that some cases are more suitable than others.
For example according to this review, IE versions of 8 and below have some buggy behaviour regarding <button> tag when trying to use it as a submit button.
Ηowever the <button> has some new attributes added in HTML5 which you can see here , ammong them is autofocus and other useful that will be supported by most modern major browsers.
In your case that you want to maintain the "focus" (i assume with tabbing support), if you use a single <image> as a button (with or without <a>), you will have to add some JS code to make the image focusable when the appropriate tab is pressed. So you will have to write a bit more code to do the same thing.
There is one more solution which might be suitable for you, since you do not need to submit the form to server side. Using the <input type="image" type and defining the src attribute inside it, will be focusable and not require neither any JS code to run nor any difficult CSS. You can find more about it's syntax here
So, it ends up to you to decide which one of all them to use.
I would use the one that i find more flexible, easier for me to code, easily reusable and is supported by most of my target browsers.
Use jQuery as you own it...
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<style type="text/css">
#theBtn{
margin: 20% auto 0;
background: url('http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/White_and_yellow_flower.JPG/320px-White_and_yellow_flower.JPG');
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<div id="theBtn"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#theBtn").click(function(){
if(confirm('Are you sure?')){
$("#theBtn").fadeOut('slow');
}
});
});
</script>
</body>
</html>
Inside a <button> tag , put your image, and attach an click event to <button> to open the dialog on click.
JSFiddle
First thing, There is either an image or a button. But not both.
I would say, create an image and place your code in the onclick() function of that image.
var img= $("#my-image-id");
image.click(function() {
// your code here
}
As I know You can't change the look of the Safari buttons thats why I suggest to use a for the solution. Here is my simple code: http://jsfiddle.net/djgBK/1/
The basis is:
Take an a element put the link content to the left,
Then replace it with image that is actualy it's background. Becouse it's a element user can select it usin only TAB button.
What's more using an a elemet will let You to put title which will be displayed after hovering/entering over the button.

Setting DIV width and height in JavaScript

I have a div with id="div_register". I want to set its width dynamically in JavaScript.
I am using this following code:
getElementById('div_register').style.width=500;
but this line of code isn't working.
I also tried using the units px like the following, still no luck:
getElementById('div_register').style.width='500px';
and
getElementById('div_register').style.width='500';
and
getElementById('div_register').style.width=500px;
but none of this code is working for me.
I don't know what's going wrong.
I am using Mozilla Firefox.
EDIT
<html>
<head>
<title>Untitled</title>
<script>
function show_update_profile() {
document.getElementById('black_fade').style.display='block';
//document.getElementById.('div_register').style.left=((window.innerWidth)-500)/20;
document.getElementById('div_register').style.height= "500px";
document.getElementById('div_register').style.width= '500px';
//alert('kutta');
document.getElementById('div_register').style.display='block';
document.getElementById('register_flag').value= 1;
document.getElementById('physical_flag').value= 0;
document.getElementById('cultural_flag').value= 0;
document.getElementById('professional_flag').value= 0;
document.getElementById('lifestyle_flag').value= 0;
document.getElementById('hobby_flag').value= 0;
//alert(window.innerWidth);
}
</script>
<style>
.white_content {
display:none;
}
</style>
</head>
<body>
<div id="main">
<input type="button" onclick="javascript:show_update_profile();" id="show" name="show" value="show"/>
</div>
<div id="div_register">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
welcome
</td>
</tr>
</table>
</div>
</body>
</html>
The properties you're using may not work in Firefox, Chrome, and other non-IE browsers. To make this work in all browsers, I also suggest adding the following:
document.getElementById('div_register').setAttribute("style","width:500px");
For cross-compatibility, you will still need to use the property. Order may also matter. For instance, in my code, when setting style properties with JavaScript, I set the style attribute first, then I set the properties:
document.getElementById("mydiv").setAttribute("style","display:block;cursor:pointer;cursor:hand;");
document.getElementById("mydiv").style.display = "block";
document.getElementById("mydiv").style.cursor = "hand";
Thus, the most cross-browser compatible example for you would be:
document.getElementById('div_register').setAttribute("style","display:block;width:500px");
document.getElementById('div_register').style.width='500px';
I also want to point out that a much easier method of managing styles is to use a CSS class selector and put your styles in external CSS files. Not only will your code be much more maintainable, but you'll actually make friends with your Web designers!
document.getElementById("div_register").setAttribute("class","wide");
.wide {
display:block;
width:500px;
}
.hide {
display:none;
}
.narrow {
display:block;
width:100px;
}
Now, I can easily just add and remove a class attribute, one single property, instead of calling multiple properties. In addition, when your Web designer wants to change the definition of what it means to be wide, he or she does not need to go poking around in your beautifully maintained JavaScript code. Your JavaScript code remains untouched, yet the theme of your application can be easily customized.
This technique follows the rule of separating your content (HTML) from your behavior (JavaScript), and your presentation (CSS).
These are several ways to apply style to an element. Try any one of the examples below:
1. document.getElementById('div_register').className = 'wide';
/* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';
Fix the typos in your code (document is spelled wrong on lines 3 & 4 of your function, and change the onclick event handler to read: onclick="show_update_profile()" and you'll be fine. #jmort's advice is good - simply set up 2 css classes that you switch between in javascript - it'll make things easier.
You might also check out element.addEventListener for assigning event handlers to your elements.
The onclick attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.
If you remove the javascript: prefix and remove the parts for the unknown ids like 'black_fade' from your javascript code, this should work in firefox
Condensed example:
<html>
<head>
<script type="text/javascript">
function show_update_profile() {
document.getElementById('div_register').style.height= "500px";
document.getElementById('div_register').style.width= "500px";
document.getElementById('div_register').style.display='block';
return true;
}
</script>
<style>
/* just to show dimensions of div */
#div_register
{
background-color: #cfc;
}
</style>
</head>
<body>
<div id="main">
<input type="button" onclick="show_update_profile();" value="show"/>
</div>
<div id="div_register">
<table>
<tr>
<td>
welcome
</td>
</tr>
</table>
</div>
</body>
</html>
Be careful of span!
myspan.styles.width='100px' doesn't want to work.
Change the span to a div.
You have to use document. The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content,
know more
document.getElementById('div_register').style.width='500px';

Categories